I have a navigation bar coded in html & css, and I am trying to add selected and deselected states to each of the buttons. I am setting the state of the first button to selected in the window.onload function like this:
<script type="text/javascript">
window.onload = function() {
var nav = document.getElementById('textContainer');
var navItems = nav.getElementsByTagName('a');
var item = navItems[0];
item.style.color = "#696969";
};
</script>
I then add event handlers in another function so that buttons can be selected and deselected:
<script type="text/javascript">
var nav = document.getElementById('textContainer');
var activeItem = null;
var navItems = nav.getElementsByTagName('a');
for (var i = 0; i < navItems.length; i++) {
navItems[i].addEventListener('click',
function() {
if (activeItem) {
activeItem.style.color = "#b3b3b3";
}
this.style.color = "#696969";
activeItem = this;
//alert(activeItem.innerText);
}, false);
}
</script>
But as I have added this, the first button, set in the window.onload function, does not deselect like the rest of the buttons, you have to click on the first button and then having done that, you can select it and deselect it at any point.
Please can you tell me where I am going wrong?
Thanks in advanced!
XcodeDev.
Try initializing
activeItemwith the first button, before you assign the event handlers: