rob.m rob.m - 5 months ago 33
jQuery Question

How to loop faster than .each through svg path and polygons?

I am drawing different svg maps. Each nation will fadeIn and fadeOut. Below I am clicking a

#compbtn
button to load a
.compMap
map using the
.compbtn
. Yet
.each
seems really slow before to process and start the fading of each polygon and path.

How can I loop faster than using
.each
?

html

<div class="oldmap">SVG old map polygons and path</div>
<div class="newmap">SVG old map polygons and path</div>
<div class="computer_all">SVG old map polygons and path</div>


NOTE:
.country
and
.shape
are the polygons and path classes i use for the sequential fadings of each part.

JS

$("#compbtn").on("click", function(i) {
var $newMap =$('.newmap .country, .newmmap .shape');
$newMap.each(function( i ){
$(this).delay(2*i).fadeTo(300,0);
});
var $oldmap = $('.oldmap .country, .oldmap .shape');
$oldmap.each(function( c ){
$(this).delay(2*c).fadeTo(300,0);
});
var lis = $('.computer_all .country, .computer_all .shape'),
len = lis.length;
lis.each(function(b) {
$(this).delay(2*b).fadeTo(500,1, function(){
if (b === len - 1) {
$(".oldmap").css("left", "-9999px");
$(".newmap").css("left", "-9999px");
}
});
});
});

Answer

Could this effect be done with (mostly) CSS? If I were doing this, I'd loop through each of the shapes and set their custom transition-delay property via the style attribute when the JavaScript loads, and use CSS selectors in the stylesheet such as .oldmap.out .shape and .computer_all.in .shape so you only have to edit the markup of the maps with jQuery in order to trigger all their fade effects with their respective delays. This avoids using a for loop entirely (at least when you need the transition to kick in).

CSS:

.newmap .country,
.newmap .shape,
.oldmap .country,
.oldmap .shape {
  opacity: 1;
  transition-property: opacity;
  transition-duration: 0.3s;
}

.newmap.out .country,
.newmap.out .shape,
.oldmap.out .country,
.oldmap.out .shape {
  opacity: 0;
}

.computer_all .country,
.computer_all .shape {
  opacity: 0;
  transition-property: opacity;
  transition-duration: 0.5s;
}

.computer_all.in .country,
.computer_all.in .shape {
  opacity: 1;
}

Startup:

$('.newmap .country, .newmmap .shape').each(function(i) {
  $(this).css('transition-delay', i/500 + 's');
});

$('.oldmap .country, .oldmap .shape').each(function(i) {
  $(this).css('transition-delay', i/500 + 's');
});

$('.computer_all .country, .computer_all .shape').each(function(i) {
  $(this).css('transition-delay', i/500 + 's');
});

Click:

$('#compbtn').click(function() {
  $('.newmap, .oldmap').addClass('out');
  $('.computer_all').addClass('in');
});
Comments