1

Please consider my apologies for this lengthy question.

Question: Not able to get the class to toggled/added through jquery.

Scenario: I have drawn a random shape using path element of svg in html. Using the css i can get the marching ants effect for the shape. I have used the below css code to do that.

.content {
  stroke-dasharray: 10 5;
  stroke-dashoffset: 1000;
  -webkit-animation: dash 15s linear infinite;
} 

@-webkit-keyframes dash {
  from {
    stroke-dashoffset: 0;
  }
  to {
    stroke-dashoffset: 1000;
  }
}

This gives a marching ants effect in one direction. If you want in another direction you have to reverse the from and to in @-webkit-keyframes.

What I want to do? I want to change the direction of the marching ants depending on the position of the cursor.

What I have done now? I have defined separate animation rules for each direction "marching" effect. here it is:

.content1 {
  stroke-dasharray: 10 5;
  stroke-dashoffset: 1000;
  -webkit-animation: dash 15s linear infinite;
}

.content2 {
  stroke-dasharray: 10 5;
  stroke-dashoffset: 1000;
  -webkit-animation: dash_reverse 15s linear infinite;
}

@-webkit-keyframes dash {
  from {
    stroke-dashoffset: 0;
  }
  to {
    stroke-dashoffset: 1000;
  }
}


@-webkit-keyframes dash_reverse {
  from {
    stroke-dashoffset: 1000;
  }
  to {
    stroke-dashoffset: 0;
  }
}

Through Javascript I am trying to determine the position of cursor and change the class of the element. Here is Javascript code:

$(document).ready(function(){
  $(document).mousemove(function(event){
    var content = $("#content");
    var left  = content.offset().left;
    var pageX = event.pageX;

    if (pageX<left) {
        $("#content").addClass("content1");
        $("#content").removeClass("content2");
        }
    else {
        $("#content").addClass("content2");
        $("#content").removeClass("content1");
        }
  });
});

but i am not getting the animation effect when i execute the javascript code. I have tried to use the toggleClass() method but no results.

Here is the JSfiddle link.

Raghavendra N
  • 1,359
  • 1
  • 18
  • 36

2 Answers2

0

I think there is no class attribute found in html.

if (pageX<left) {
    $("#content").attr("class","content1");
    }
else {
    $("#content").attr("class","content2");
    }
Punitha Subramani
  • 1,467
  • 1
  • 8
  • 6
0

The problem is that jQuery does not support classes of SVG elements, thats why you have to use .attr() method instead of .addClass() .removeClass().

Nice explanations and examples in old ticket: jQuery SVG, why can't I addClass?

Community
  • 1
  • 1
Tomor
  • 814
  • 6
  • 10