Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing text color onclick and change back for other items

I found this in another question/answer and modified it... but it still doesn't work. I'm a js-noob, so.. could someone please help me out? It's probably simple...

<script>
    document.getElementById('change').onclick = changeColor;   
    function changeColor() {
        document.body.style.color = "red";
        return false;
    }   
</script>

<div id="myid" onclick="changeColor(this); return false;">Hello Here !!</div><br>
<div id="myid2" onclick="changeColor(this); return false;">Hello There !!</div><br>

My issue is: When I run this, both should have black color. When I click on the first, ONLY THAT one should turn red. If after that I click on the second one, the first one should be black again and only the second one red... How do I do this? (jquery would be welcome as well, if that has a solution...)

Thanks!

like image 804
Malachi Avatar asked Feb 23 '23 09:02

Malachi


1 Answers

Thank you Edwin. I did some googling and fiddled around with something I found and it does exactly what I want to do. Sorry for the confusion.. I picked the divs and if I could get that to work, then I would implement it for my li's.. Anyway, the solution is:

javascript part:

function switchColors(element)  
{  
links=document.getElementsByTagName("li") ;  
for (var i = 0 ; i < links.length ; i ++)  
links.item(i).style.color = 'black' ;  
element.style.color='orange' ;  
}  

and the html stuff that needed the color change:

<ul>  
<li onclick="switchColors(this);">Link 1</li>  
<li onclick="switchColors(this);">Link 2</li>  
<li onclick="switchColors(this);">Link 3</li>  
</ul>  
like image 72
Malachi Avatar answered May 07 '23 21:05

Malachi