Skip to content
Advertisement

Can jQuery .each be used when setting an interval within that sets an element’s .html()?

I have a page with multiple .countdown-element divs which I want to contain a countdown.

I am iterating through each .countdown-element and attempting to apply a countdown timer to each of them.

The $(this).html() parts in the setInterval do not trigger. I assume this is related to using .each and it’s going through the other .countdown-element divs before it can run.

How can I get the countdown to be applied to each of the .countdown-element divs?

JavaScript

Div markup is (note the data attribute here is dynamic from PHP hence why I need to apply it as an attribute and use that from the JS):

JavaScript

Advertisement

Answer

The this inside the setInterval is callback is not the same this as inside the .each

Take a copy of this inside the .each and use that, eg:

JavaScript

Alternatively, depending on your browser, use => to preserve this into the callback

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement