Malachi
Malachi

Reputation: 977

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!

Upvotes: 4

Views: 32693

Answers (2)

Edwin
Edwin

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:

  1. The first line of script gets an element with ID 'change'. No such ID exists in your HTML.
  2. document.body does not return a valid JavaScript object with which you can access .style.color.
  3. changeColor() does not accept any arguments, so you should not be calling it with changeColor(this).
  4. Do not use inline DOM. I.e., do not use the onclick attribute in the HTML. HTML is meant for layout, not scripting.
  5. (Added by @roselan in the comments below) Instead of using $.css or JavaScript's native .style, use predefined CSS style rules and switch elements' classes to get the desired effect. (an example of this practice can be found in the solution.)

And most importantly, layout should remain in HTML, scripting in JavaScript, and styling in CSS.

Upvotes: 4

Malachi
Malachi

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

Related Questions