Reputation: 20409
I have the following script:
<script>
window.now = some_int_value;
</script>
and the following html:
<span class="dot"></span>
<span class="dot active"></span>
<span class="dot"></span>
<span class="dot"></span>
How should I change the style of the dot in accordance with window.now
value? So, if it is equal to 1, then first dot should be 'dot active', if equal to 2, then second and so on.
Upvotes: 0
Views: 580
Reputation: 185893
This should do it:
var dots = document.querySelectorAll( '.dot' );
[].slice.call( dots ).forEach( function ( dot, i ) {
dot.className = 'dot' + ( window.now === i + 1 ? ' active' : '' );
});
(This doesn't work in IE8.)
Live demo: http://jsfiddle.net/dKDLx/
(The demo shows that even though the 2. dot had the class "active" set, window.now = 3;
will cause that class to be "moved" to the 3. dot.)
Upvotes: 1
Reputation: 11044
You should consider looking into jQuery, which simplifies working with the DOM a lot.
This is all you'd need for your indicator in jQuery:
$('span.dot').eq(window.now - 1).addClass('active');
No more
Upvotes: 1
Reputation: 78520
document.getElementsByClassName("dot")[window.now-1].className += " active";
You can do that (for IE9+ and all other major browsers).
Or you can use
document.querySelectorAll(".dot")[window.now-1].className += " active";
for IE8+, FF3+, and all other major browsers.
or you can combine them
if(document.getElementsByClassName);
document.getElementsByClassName("dot")[window.now-1].className += " active";
else if(document.querySelectorAll)
document.querySelectorAll(".dot")[window.now-1].className += " active";
Upvotes: 1
Reputation: 88
This isn't, by any chance, supposed to be a 4-dot progress bar/throbber? If so, I'd say just use a gif - there's a site that can generate them for you: http://preloaders.net/
Upvotes: 0