javascript - Loop through divs and toggle class if another class exists -


i want toggle class (and make text blink using interval) if class found.

css

.flash {     color: #dc4900; } 

html

<div class="text notify">flash</div> <div class="text notify">flash</div> <div class="text">don't flash</div> 

js

$(document).ready(function() {   $('.text').each(function() {     if ($(this).hasclass('notify')) {       setinterval(function() {         $(this).toggleclass('flash');       }, 1000);     }   }); }); 

https://jsfiddle.net/s9dv9qv3/

the interval not working should. should adding flash class text if class notify found.

inside of setinterval callback, this refers window object.

to work around this, 1 option capture reference this outside of callback:

example here

$('.text.notify').each(function() {   var self = this;    setinterval(function() {     $(self).toggleclass('flash');   }, 1000); }); 

i removed check notify class since can select elements directly.


alternatively, use .bind() method set value of this:

example here

$('.text.notify').each(function() {   setinterval(function() {     $(this).toggleclass('flash');   }.bind(this), 1000); }); 

as side note, since you're toggling class on of elements @ same time, use:

setinterval(function() {   $('.text.notify').toggleclass('flash'); }, 1000); 

if want set delay, add timeout based on current index of .each() loop:

example here

$('.text.notify').each(function(i) {   var self = this;    settimeout(function() {     setinterval(function() {       $(self).toggleclass('flash');     }, 1000);   }, 1000 * i); }); 

lastly, can avoid jquery , use infinite css3 animation:

.text.notify {    animation: flash 2s infinite;  }  @keyframes flash {    0%, 49% {      color: #000;    }    50%, 100% {      color: #dc4900;    }  }
<div class="text notify">flash</div>  <div class="text notify">flash</div>  <div class="text notify">flash</div>  <div class="text notify">flash</div>  <div class="text">don't flash</div>


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -