Reputation: 977
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!
Upvotes: 4
Views: 32693
Reputation: 2114
Here's your solution.
It's not the best, but considering the mistakes you made copying the code, you might want to check out Wikiversity's page on Beginning JavaScript, as well as their challenges.
Also, a list of errors in the code you copied, so you can avoid these problems again:
document.body
does not return a valid JavaScript object with which you can access .style.color
.changeColor()
does not accept any arguments, so you should not be calling it with changeColor(this)
.onclick
attribute in the HTML. HTML is meant for layout, not scripting.And most importantly, layout should remain in HTML, scripting in JavaScript, and styling in CSS.
Upvotes: 4
Reputation: 977
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>
Upvotes: 4