Tips for adding a gradient to your design instead of a plain solid color

I stumbled upon a snippet on CSS Tricks

Attempting to replace the green color with a gradient value, but unfortunately, the value is not being applied. I have tried using both the fill property and gradient color, but neither has been successful.

Here is the code:

const FULL_DASH_ARRAY = 283;

const TIME_LIMIT = 20;
let timePassed = 0;
let timeLeft = TIME_LIMIT;
let timerInterval = null;

document.getElementById("app").innerHTML = `
<div class="base-timer">
  <svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
    <g class="base-timer__circle">
      <circle class="base-timer__path-elapsed" cx="50" cy="50" r="45"></circle>
      <path
        id="base-timer-path-remaining"
        stroke-dasharray="283"
        class="base-timer__path-remaining green"
        d="
          M 50, 50
          m -45, 0
          a 45,45 0 1,0 90,0
          a 45,45 0 1,0 -90,0
        "
      ></path>
    </g>
  </svg>
  <span id="base-timer-label" class="base-timer__label">${formatTime(
    timeLeft
  )}</span>
</div>
`;

startTimer();

function onTimesUp() {
  clearInterval(timerInterval);
}

function startTimer() {
  timerInterval = setInterval(() => {
    timePassed = timePassed += 1;
    timeLeft = TIME_LIMIT - timePassed;
    document.getElementById("base-timer-label").innerHTML = formatTime(
      timeLeft
    );
    setCircleDasharray();

    if (timeLeft === 0) {
      onTimesUp();
    }
  }, 1000);
}

function formatTime(time) {
  const minutes = Math.floor(time / 60);
  let seconds = time % 60;

  if (seconds < 10) {
    seconds = `0${seconds}`;
  }

  return `${minutes}:${seconds}`;
}



function calculateTimeFraction() {
  const rawTimeFraction = timeLeft / TIME_LIMIT;
  return rawTimeFraction - (1 / TIME_LIMIT) * (1 - rawTimeFraction);
}

function setCircleDasharray() {
  const circleDasharray = `${(
    calculateTimeFraction() * FULL_DASH_ARRAY
  ).toFixed(0)} 283`;
  document
    .getElementById("base-timer-path-remaining")
    .setAttribute("stroke-dasharray", circleDasharray);
}
body {
  font-family: sans-serif;
  display: grid;
  height: 100vh;
  place-items: center;
}

.base-timer {
  position: relative;
  width: 300px;
  height: 300px;
}

.base-timer__svg {
  transform: scaleX(-1);
}

.base-timer__circle {
  fill: none;
  stroke: none;
}

.base-timer__path-elapsed {
  stroke-width: 7px;
  stroke: grey;
}

.base-timer__path-remaining {
  stroke-width: 7px;
  stroke-linecap: round;
  transform: rotate(90deg);
  transform-origin: center;
  transition: 1s linear all;
  fill-rule: nonzero;
  stroke: currentColor;
}

.base-timer__path-remaining.green {
  color: rgb(65, 184, 131);
}

.base-timer__label {
  position: absolute;
  width: 300px;
  height: 300px;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
}
<div id="app"></div>

Would it be possible to apply a gradient only to the progress bar (green) of the SVG, or is gradient usage disallowed in SVG?

Answer №1

Have you found what you were searching for?

const FULL_DASH_ARRAY = 283;

const TIME_LIMIT = 20;
let timePassed = 0;
let timeLeft = TIME_LIMIT;
let timerInterval = null;

document.getElementById("app").innerHTML = `
<div class="base-timer">
  <svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
   <defs>
   <linearGradient id="linear" x1="0%" y1="0%" x2="100%" y2="0%">
     <stop offset="0%"   stop-color="#05a"/>
     <stop offset="50%"  stop-color="#a55"/>
     <stop offset="100%" stop-color="#0a5"/>
   </linearGradient>
 </defs>
    <g class="base-timer__circle">
      <circle class="base-timer__path-elapsed" cx="50" cy="50" r="45"></circle>
      <path
        
        id="base-timer-path-remaining"
        stroke=url(#linear)
        stroke-dasharray="283"
        
        class="base-timer__path-remaining green"
        d="
          M 50, 50
          m -45, 0
          a 45,45 0 1,0 90,0
          a 45,45 0 1,0 -90,0
        "
      ></path>
    </g>
  </svg>
  <span id="base-timer-label" class="base-timer__label">${formatTime(
    timeLeft
  )}</span>
</div>
`;

startTimer();

function onTimesUp() {
  clearInterval(timerInterval);
}

function startTimer() {
  timerInterval = setInterval(() => {
    timePassed = timePassed += 1;
    timeLeft = TIME_LIMIT - timePassed;
    document.getElementById("base-timer-label").innerHTML = formatTime(
      timeLeft
    );
    setCircleDasharray();

    if (timeLeft === 0) {
      onTimesUp();
    }
  }, 1000);
}

function formatTime(time) {
  const minutes = Math.floor(time / 60);
  let seconds = time % 60;

  if (seconds < 10) {
    seconds = `0${seconds}`;
  }

  return `${minutes}:${seconds}`;
}



function calculateTimeFraction() {
  const rawTimeFraction = timeLeft / TIME_LIMIT;
  return rawTimeFraction - (1 / TIME_LIMIT) * (1 - rawTimeFraction);
}

function setCircleDasharray() {
  const circleDasharray = `${(
    calculateTimeFraction() * FULL_DASH_ARRAY
  ).toFixed(0)} 283`;
  document
    .getElementById("base-timer-path-remaining")
    .setAttribute("stroke-dasharray", circleDasharray);
}
body {
  font-family: sans-serif;
  display: grid;
  height: 100vh;
  place-items: center;
}

.base-timer {
  position: relative;
  width: 300px;
  height: 300px;
}

.base-timer__svg {
  transform: scaleX(-1);
}

.base-timer__circle {
  fill: none;
  stroke: none;
}

.base-timer__path-elapsed {
  stroke-width: 7px;
  stroke: grey;
}

.base-timer__path-remaining {
  stroke-width: 7px;
  stroke-linecap: round;
  transform: rotate(90deg);
  transform-origin: center;
  transition: 1s linear all;
  fill-rule: nonzero;
}

.base-timer__path-remaining.green {
  /*stroke: red;*/
}

.base-timer__label {
  position: absolute;
  width: 300px;
  height: 300px;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
}
<div id="app"></div>

Answer №2

One of the capabilities in CSS is the background-image property, allowing you to add gradients to text and other elements.

For instance:

background-image: linear-gradient(blue, green);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the routing to fail in this script?

Currently working on a small project to dive into AngularJS, and I'm facing some challenges with getting the routing to function properly. Despite following numerous tutorials, my code doesn't seem to be working as expected. If anyone could lend ...

Toggle Visibility of Elements with Javascript and Html

I've been working on implementing a "Show All / Hide All" feature. Currently, clicking on the text opens the image and text individually. However, I am looking to add a functionality for expanding all divs at once. To see how it currently functions, ...

css optimizing image content for search engine visibility

My website's main page features a div with an image containing the message "contact us by calling 1 800 blabla..". I'm concerned that search engines may not be able to recognize or find my company's phone number since it is only displayed wi ...

"Guidelines for implementing a post-login redirection to the homepage in React with the latest version of react-router (v

I am facing an issue where I am unable to redirect to the Home Page when I click the "Login" button during my React studies. Despite trying all possible methods for redirects, none of them seem to work. The function that is executed when I click the "logi ...

Transforming functions with dependencies into asynchronous operations with the help of promises

Can I convert both of my functions into asynchronous functions, even though one function relies on the other? Is it feasible for function b to execute only after function a? ...

Tips for aligning and emphasizing HTML content with audio stimuli

I am looking to add a unique feature where the text highlights as audio plays on a website. Similar to what we see on television, I would like the text to continue highlighting as the audio progresses. Could someone please provide me with guidance on how ...

Angular JS: How to dynamically add and remove checkboxes in ng-repeat?

Currently, I have successfully implemented a Miller column using Angular and Bootstrap. To view the functionality in action, you can check out the code snippet at this link. In the second column of my setup, clicking on a word opens up the third column. ...

Mobile browser not resizing window width in fluid layout on WordPress site

Currently, I am working on developing a basic web layout that can adapt to mobile view. I have made some progress which you can check out here. The layout successfully adjusts when the window is resized in Firefox or Chrome. However, when I tried to acce ...

Incorporate additional form element functionalities using radio inputs

Recently, I created code that allows a user to duplicate form elements and add values by clicking on "add more". Everything is functioning properly except for the radio inputs. I am currently stuck on this issue. Does anyone have any suggestions on how I c ...

Tips for integrating SASS from the Bulma package into an Angular application

I'm currently working on implementing Bulma into my project. The documentation suggests using NPM to obtain it. yarn add bulma Further in the documentation, there is an example provided with code snippets like the ones below. <link rel="styles ...

Tips for maximizing efficiency and minimizing the use of switch conditions in JavaScript when multiple function calls are needed

After coming up with this code a few minutes ago, I began to ponder if there was a more elegant way to optimize it and condense it into fewer lines. It would be even better if we could find a solution that eliminates the need for the switch condition altog ...

Discovering whether a link has been clicked on in a Gmail email can be done by following these steps

I am currently creating an email for a marketing campaign. In this email, there will be a button for users to "save the date" of the upcoming event. I would like to implement a feature that can detect if the email was opened in Gmail after the button is cl ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

The Architecture of a Node.js Application

I'm curious about the efficiency of my nodejs app structure in terms of performance optimization. My main concern lies in how I handle passing around references to my app object across modules. Basically, in my app.js file, I define all my dependenci ...

Validating HTML using EJS templates set as "text/template" elements

What is the general consensus on HTML validation when utilizing a framework such as Backbone or Meteor and generating views in the client from EJS templates? An issue arises with the fact that name is not considered an official attribute for a <script& ...

Creating an array object in TypeScript is a straightforward process

Working on an Angular 4 project, I am attempting to declare an attribute in a component class that is an object containing multiple arrays, structured like this: history: { Movies: Array<Media>, Images: Array<Media>, Music: Array<Medi ...

Graph not displaying dates on the x-axis in flot chart

I've been attempting to plot the x-axis in a Flot chart with dates. I've tried configuring the x-axis and using JavaScript EPOCH, but have had no success so far. Here's a snippet of my code: <?php foreach($data[0] as $i => $d){ ...

Why is my event.target.value not updating correctly in React useState?

My problem is that when I use useState, I am receiving incorrect numbers For example, if I print e.target.value it might display 1, but my selectedIndex shows 2. Similarly, when I have a selectedIndex of 0, it retrieves something different like 1. Any tho ...

Enhance your WooCommerce shopping experience by incorporating a variety of personalized checkout fields organized into two distinct

I have implemented custom code to create unique checkout fields based on the number of products in a customer's cart. Each product requires 4 customized checkout fields, displayed in two columns side by side. The expected result is as follows: co ...

Encountering difficulties in sending a JavaScript array through jQuery ajax request

I'm feeling hesitant to ask this, but I can't figure out why my code isn't working. Here's what I have: <script> var formArray = new Array(); formArray['start'] = "one"; formArray['stopat'] = "two"; formArray ...