Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic transition from one color to another.

Here is a snapshot showing a few frames of the animation: svg animation
Despite exploring various techniques, I have yet to discover an optimal solution.
I attempted implementing it using CSS keyframes:

    $.keyframe.define([{
      name: 'shift',
      ...
      ...
      
    }]);
    $('.ledbar').playKeyframe({
        name: 'shift',
        duration: "4s",
        timingFunction: 'linear',
        delay: 0,
        direction: 'reverse',
        fillMode: 'forwards',

      });

The orange part should move over the green areas of the svg. Each rectangle in the svg was designed to be incrementally 6px further than the previous one. However, due to the smooth transition between keyframes, the animation flickers. Transitioning the animation step by step might resolve this issue, but I'm unsure how to execute this effectively.

Hence, my query revolves around achieving a linear color shift within the svg to another color. I've explored options like svg masks without success.

If you find it helpful, here is the svg file:

    <?xml version="1.0" encoding="utf-8"?>
...
...
</svg>

Answer №1

One creative method involves using an animated linear gradient.

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="403.5px" height="13px" viewBox="0 0 403.5 13" enable-background="new 0 0 403.5 13" xml:space="preserve">
<defs>
  <linearGradient id="orange-grad" gradientUnits="userSpaceOnUse">
    <stop offset="0" stop-color="orange"/<
    <stop offset="0" stop-color="orange">
      <animate attributeName="offset" attributeType="XML"
               begin="0s" dur="5s" fill="freeze" from="0" to="1" />
    </stop>
    <stop offset="0" stop-color="#80A993">
      <animate attributeName="offset" attributeType="XML"
               begin="0s" dur="5s" fill="freeze" from="0" to="1" />
    </stop>
    <stop offset="1" stop-color="#80A993"/>
  </linearGradient>
</defs>
<g fill="url(#orange-grad)">
    <path d="M0.017,0L1.5,0.002L1.484,13H0L0.017,0z"/>
    <path d="M6.017,0L7.5,0.002L7.484,13H6L6.017,0z"/>
    <path d="M12.017,0L13.5,0.002L13.484,13H12L12.017,0z"/>
    ...
    (Additional path elements are present in the SVG)
</g>
</svg>

Update: Technique for manual activation and direction change

This updated approach uses a different technique to create the graph by employing a clipping path and moving an orange rectangle behind the clip. To meet the request of the original poster, functionality has been added to trigger and alter the animation direction with mouseover actions on buttons.

In this example, vanilla Javascript is utilized along with a timeout function for the animation. For smoother performance under heavier page loads, switching to window.requestAnimationFrame() can be considered.

var graphPosition = 0;
var graphStep = 6;
var graphRunning = false;

var orangeRect = document.getElementById("orange");


document.getElementById("forwards").addEventListener("mouseenter", function() {
  graphStep = 6;
  startGraphRunning();
});

document.getElementById("backwards").addEventListener("mouseenter", function() {
  graphStep = -6;
  startGraphRunning();
});



function startGraphRunning()
{
  // Avoid redundant operation if already running
  if (graphRunning) return;

  graphRunning = true;

  // Initiate the initial step of animation
  animationStep();
}


function animationStep()
{
  // Calculate new position of orange rectangle
  var  newPos = graphPosition += graphStep;
  if (newPos < 0 || newPos > 408)
  {
    // Halt animation upon reaching minimum or maximum positions
    graphRunning = false;
  }
  else
  {
    // Update x position of orange rect
    graphPosition = newPos;
    // Positioning logic based on desired edge location of rectangle
    orangeRect.setAttribute("x", graphPosition - orangeRect.width.baseVal.value);
  }

  // Keep animation active by calling this function after 50ms if still running
  if (graphRunning)
    setTimeout(animationStep, 50);
}
div {
  display: inline-block;
  padding: 10px;
  background-color: #eee;
  border: solid 1px black;
  margin: 20px 20px 0 0;
}
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="403.5px" height="13px" viewBox="0 0 403.5 13" enable-background="new 0 0 403.5 13" xml:space="preserve">
<defs>
  <clipPath id="graph">
    <path d="M0.017,0L1.5,0.002L1.484,13H0L0.017,0z"/>
    <path d="M6.017,0L7.5,0.002L7.484,13H6L6.017,0z"/>
    <path d="M12.017,0L13.5,0.002L13.484,13H12L12.017,0z"/>
    ...
    (Additional path elements are present in the clipping path definition)
  </mask>
</defs>

<g clip-path="url(#graph)">
  <rect x="0" y="0" width="408" height="13" fill="green"/>
  <rect x="-408" y="0" width="408" height="13" fill="orange" id="orange"/>
</g>

</svg>

<br />
<div id="forwards">Forwards</div>
<div id="backwards">Backwards</div>

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

Issue with utilizing display: table and overflow: hidden in Internet Explorer and Firefox, functioning properly on Webkit and Blink

JSFiddle : http://jsfiddle.net/h7xvr2t9/2/ I have been experimenting with ways to achieve some effects: Animating a hidden DIV to slide into view from below a visible container Centering text/image on a link to trigger the animation HTML <div clas ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

Navigate divs with varying z-index values

I want to change the z-index of 3 divs by toggling them using jQuery, but I'm not sure how to do it. What I want is to click a button that relates to a specific div and increase the z-index of that div so the content inside it is shown. Currently, all ...

Empty Array returned in VueJS after Axios GET request | VUEJS/LARAVEL

Currently, I am working on a project for my university while also learning how to build a single page application through a Udemy course. The issue I'm facing is related to pushing data from a JSON database query named "alunos" to the front end using ...

Attempting to set up an Ajax webform with various outputs, but encountering issues with functionality

I'm encountering an issue while creating interactive exercises. I want to display correct or incorrect answers immediately after submission using JSON for retrieving responses, as suggested in a forum. However, my AJAX code isn't working at all. ...

Is it possible to utilize Flask in conjunction with jQuery's POST method?

I have just started learning Flask and before I move forward, I would like to know if it is possible to send a "post" request from jQuery to a Python function using Flask and JSON. I am not very familiar with JSON either, so all the code examples seem quit ...

I am looking to set an HTML file as the homepage for my Next.js project

Is there a way in next.js to render a normal .html file (index.html) when someone visits my root directory at "https://example.com/"? I have researched and edited my config file as shown below, /** @type {import('next').NextConfig} */ const next ...

Leveraging jQuery for Crafting a Quiz with True or False Questions

Exploring the most effective approach to constructing a questionnaire. Find images below for reference. The current code setup is functional but becomes lengthy after just two questions. How can I streamline this code to minimize repetition? // prevent d ...

What is the best way to position href text on the top of a rectangular div box?

Whenever I try to position the text above the rectangle, it disables the link. How can I resolve this issue? Additionally, when attempting to change the color of the "San Diego" text, I'm unable to adjust its position. Just a heads up, I am new to HT ...

Improving the Speed of ASP.NET TreeView

How can we optimize performance when using the TreeView component? When I say optimize performance, I am referring to reducing the number of client-server trips, such as postbacks. Does this imply that the majority of the business logic will need to be i ...

Using Socket.IO in Node.js to distribute information to every connected client

Currently, I am in the process of developing a WebGL multiplayer game. My approach involves using socket.io and express in node.js to enable multiplayer functionality. However, I am encountering an issue with broadcasting key events. When a user presses a ...

Performing updates on Meteor.users collection while handling a promise rejection (leveraging fcm-push with Meteor)

My current project involves the use of an NPM package called fcm-push in order to send FCM notifications to different mobile devices based on specific messages. Everything works fine when the message is successfully sent, but if the sending fails due to th ...

Disabling modal popup buttons in Bootstrap 4 using Javascript

JSFiddle DEMO: https://jsfiddle.net/2yx16k8L/ I'm encountering an issue with my JS code. I want a click on a div to open the entire content within it. However, this action is causing the modal button in the dropdown to stop working. How can I resolve ...

Utilizing the same function for both keydown and click events

I'm currently exploring how to activate the same jQuery function when clicking on an anchor tag or pressing the L key. Here is where I'm starting from: jQuery('body').on('click','.jm-post-like',function(event){ ...

Fetching the "User ID" variable from localStorage to PHP with angularjs - a quick guide

My goal is to retrieve "Notes" based on the "userID" value. Here is my approach: I used angular.js to trigger the PHP function $scope.getData = function(){ $http.get( '../php/displayNotes.php' ).success(function(data){ $ ...

Encountering a problem with server-side jQuery autocomplete

I attempted to utilize a customized service I created in order to make this jquery autocomplete example work, but unfortunately it's not functioning properly. Here is the code snippet: $( "#city" ).autocomplete({ source: function( request, res ...

Navigate the child div while scrolling within the parent div

Is there a way to make the child div scroll until the end before allowing the page to continue scrolling when the user scrolls on the parent div? I attempted to use reverse logic Scrolling in child div ( fixed ) should scroll parent div Unfortunately, it ...

React Material-ui Dropdown Component

Once I completed my application, I decided to enhance its appearance using Material UI. During the transition from HTML to Material UI, a warning started appearing when selecting an item: index.js:1 Warning: findDOMNode is deprecated in StrictMode. findDO ...

Is it possible to submit a form using AJAX in WordPress without relying on WordPress functions?

As I work on constructing a website using Wordpress, I am encountering an issue with submitting a form via ajax. I'm wondering if it's possible to achieve this without relying on Wordpress functions. Currently, my code runs without errors and dis ...

Using AJAX calls with React through JQuery

How can I make a JQuery AJAX call in react js instead of using the fetch method? I have an environment restriction that requires me to use JQuery Ajax for getting json format data from a URL. The code snippet below shows my current implementation using t ...