samedi 3 novembre 2018

Jquery add class if a corresponding element hasClass 'active' (trying to streamline my code)

Please help - there must be a better way to do this! So basically, in an svg I have a bunch of elements with class names 1 - 50. And then a bunch of corresponding elements with id's 1 - 50. In a nutshell - if circle 1 has class hotspot-active then path 1 should have class locator-active and so on.

My code works but I really don't want to write 50 if statements! I'm sure this can be done with arrays but my Jquery just isn't good enough. Any help would be massively appreciated. Here is a small code example from 1 to 3 -

$(document).ready(function(){

if ($('.1').hasClass('hotspot-active') ) {
$('#1').addClass('locator-active');
}

});

$(document).ready(function(){

if ($('.2').hasClass('hotspot-active') ) {
$('#2').addClass('locator-active');
}

});

$(document).ready(function(){

if ($('.3').hasClass('hotspot-active') ) {
$('#3').addClass('locator-active');
}

});

And the HTML will look something like this -

<circle class="1" cx="1078.34" cy="656.84" r="12.75"/>
<circle class="2" cx="1547.13" cy="613.3" r="12.75"/>
<circle class="3 hotspot-active" cx="1578.15" cy="221.17" r="12.75"/>

<path id="1" />
<path id="2" />
<path id="3" />

Aucun commentaire:

Enregistrer un commentaire