I have a page with ul generated by handlebarsJS. It's like:

<ul>
    <li><a href=#>asd</a></li>
</ul>

but with more li's.
I want to change the background color of a li element when it is clicked to one color and change the previously clicked li's background color to another. All of the li elements have:

onclick="changeColor(event)"

.
When I click the first element its background color flashesh for a second and returns back to its previous color. I've debugged it and found out that it returns when the debugger goes through the </body> tag. On the other hand when i click another link the desired background color stays...forever.

This is the javascript function I use to change the color:

function changeColor (event) {
    var navTabs = document.querySelectorAll(".navtab");
    for (var i = 0; i < navTabs.length; i++) {
        navTabs[i].style.backgroundColor =  "rgb(128,0,255)";
        console.log(navTabs[i]);
    }
    event.target.style.backgroundColor = "rgb(200,191,231)";
};

And finally this is the console log every time the function has finished.

<li class="navtab" onclick="changeColor(event)" style="background-color: rgb(128, 0, 255);">…</li>
<li class="navtab" onclick="changeColor(event)" style="background-color: rgb(128, 0, 255);">…</li>
<li class="navtab" onclick="changeColor(event)" style="background-color: rgb(128, 0, 255);">…</li>
<li class="navtab" onclick="changeColor(event)" style="background-color: rgb(128, 0, 255);">…</li>

Here are some photos for clarity:
http://postimg.org/image/csl019djn/full/
http://postimg.org/image/3uxcfppgr/full/

Now it's clear to me that I'm doing something wrong, but I can't figure out what. And is there a better way to do this?

If you only have the two colours, the easiest thing to do is change the background to the default colour for all LI's and then adjust the colour for the one that was clicked using this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.