rob.m rob.m - 1 year ago 72
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

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

How can I loop faster than using


<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>

are the polygons and path classes i use for the sequential fadings of each part.


$("#compbtn").on("click", function(i) {
var $newMap =$('.newmap .country, .newmmap .shape');
$newMap.each(function( i ){
var $oldmap = $('.oldmap .country, .oldmap .shape');
$oldmap.each(function( c ){
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 Source

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 .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).


.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;
} .country, .shape {
  opacity: 1;


$('.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');


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