Javascript onmouseover and onmouseout

user2628521 picture user2628521 · Nov 16, 2013 · Viewed 25.8k times · Source

You can see in the headline what it is. I've four "div", and therein are each a p tag. When I go with the mouse on the first div, changes the "opacity" of the p tag of the first div. The problem is when I go on with the mouse on the second or third "div" only changes the tag "p" from the first "div". It should changes the their own "p" tags. And it is important, that i cannot use CSS ":hover". The problem is clear, it is that all have the same "id". I need a javascript which does not individually enumerated all the different classes.

I' sorry for my english. I hope you understand me. My script:

<div onmouseout="normal();" onmouseover="hover();" >
    <p id="something">LOLOL</p>
</div>
<div onmouseout="normal();" onmouseover="hover();" >
    <p id="something">LOLOL</p>
</div>
<div onmouseout="normal();" onmouseover="hover();" >
    <p id="something">LOLOL</p>
</div>
<div onmouseout="normal();" onmouseover="hover();" >
    <p id="something">LOLOL</p>
</div>

Javascript:

function normal() {
var something = document.getElementById('something');
something.style.opacity = "0.5";
}
function hover() {
var something = document.getElementById('something');
something.style.opacity = "1";

CSS:

p {
    opacity: 0.5;
    color: red;
}

Answer

mastazi picture mastazi · Nov 16, 2013

As Paul S. suggests, you need to pass this to the function so that it knows which element it has to work on.

<div onmouseout="normal(this);" onmouseover="hover(this);" >
    <p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
    <p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
    <p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
    <p>LOLOL</p>
</div>

And then select the child element <p> for the passed <div>. Here I select the first child p, i.e. the first element in the array of children of this element with tag p, that's why you see [0]. So if in each div you had two paragraph, then you could use e.g. getElementsByTagName("p")[1] to select the second <p>.

function normal(mydiv) {
    mydiv.getElementsByTagName("p")[0].style.opacity="0.5";
}
function hover(mydiv) {
    mydiv.getElementsByTagName("p")[0].style.opacity="1";
}

See the working example here: http://jsfiddle.net/mastazi/2REe5/