Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  154] [ 2]  / answers: 1 / hits: 28582  / 11 Years ago, sat, november 16, 2013, 12:00:00

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;
}

More From » html

 Answers
4

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/


[#74259] Thursday, November 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bethv

Total Points: 215
Total Questions: 101
Total Answers: 89

Location: Angola
Member since Wed, Jun 2, 2021
3 Years ago
;