2

I would like to loop through each h1 > a element, add and then remove a class after a certain delay, but it isn't working.

What am I doing wrong?

$("h1 a").each(function() {
  $(this).addClass('glow').delay(2000).removeClass('glow');
});
a {
  color: #000;
  text-decoration: none;
  text-shadow: -1px 0px 1px rgba(150, 150, 150, 1);
}

h1 {
  text-align: center;
}

.glow {
  animation: glow .8s infinite alternate;
}

@keyframes glow {
  to {
    text-shadow: 0 0 6px #aaa;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>
  <a href="#">wellcome</a>,&nbsp;
  <a href="#">bonjoure</a>,&nbsp;
  <a href="#">bienvenido</a>,&nbsp;
  <a href="#">benvenuto</a>,<br/>
  <a href="#">добро пожаловать</a>,<br/>
  <a href="#">willkommen</a>
</h1>
leonheess
  • 16,068
  • 14
  • 77
  • 112
wfx
  • 53
  • 2
  • 5

2 Answers2

4

Okay, forget what I said. This works - but not the css animation, that you're on your own.

var a = [];
$("h1 a").each(function(index) {
  a[index] = $(this);
  setTimeout(function() {
    a[index].addClass('glow').delay(500).queue(function(next) {
      a[index].removeClass('glow');
      next();
    });
  }, index * 500);
});
a {
  color: #000;
  text-decoration: none;
  text-shadow: -1px 0px 1px rgba(150, 150, 150, 1);
}

h1 {
  text-align: center;
}

.glow {
  background-color: yellow;
}

@keyframes glow {
  to {
    text-shadow: 0 0 6px #aaa;
  }
}
<h1>
  <a href="#">wellcome</a>,&nbsp;
  <a href="#">bonjoure</a>,&nbsp;
  <a href="#">bienvenido</a>,&nbsp;
  <a href="#">benvenuto</a>,<br/>
  <a href="#">добро пожаловать</a>,<br/>
  <a href="#">willkommen</a>
</h1>

Used these as reference:

How to make delay between each loops of jQuery.each function? Callback to .delay()

leonheess
  • 16,068
  • 14
  • 77
  • 112
dmgig
  • 4,400
  • 5
  • 36
  • 47
1

If you want to give glowing effect and class should be added and removed after sometime to give effect,you can use setInterval() like this:

$("h1").each(function(i, item) {
  setInterval(function() {
    $(item).addClass('glow');

  }, 2000 + i)
  setInterval(function() {
    $(item).removeClass('glow');

  }, 2000 + i)

});
a {
  color: #000;
  text-decoration: none;
  text-shadow: -1px 0px 1px rgba(150, 150, 150, 1);
}

h1 {
  text-align: center;
}

.glow {
  animation: glow .8s infinite alternate;
}

@keyframes glow {
  to {
    text-shadow: 0 0 6px #aaa;
  }
}
<h1>
  <a href="#">wellcome</a>,&nbsp;
  <a href="#">bonjoure</a>,&nbsp;
  <a href="#">bienvenido</a>,&nbsp;
  <a href="#">benvenuto</a>,<br/>
  <a href="#">добро пожаловать</a>,<br/>
  <a href="#">willkommen</a>
</h1>
leonheess
  • 16,068
  • 14
  • 77
  • 112
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160