Reputation: 23
I'm new in JavaScript and I'm tring to find out how I can use the same function to different elements in JavaScript.
I.e. how to set the id value for document.getElementById
in the function. I do not know why my code does't work.
JavaScript
function onhover(imgx)
{
var x = imgx;
document.getElementById('x').style.opacity=0.5;
}
HTML
<img id="img1" src="img1.jpg" onmouseout="onhover('img1')">
<img id="img2" src="img2.jpg" onmouseout="onhover('img2')">
Upvotes: 1
Views: 576
Reputation: 9080
I have created codebin for you please check using below link.
http://codebins.com/codes/home/4ldqpcc
Upvotes: 0
Reputation: 38345
Make a trivial change to your code - remove the single quotes around x
. When you use single- or double-quotes, you're passing the string "x" rather than the value of the variable x
.
function onhover(imgx)
{
var x = imgx;
document.getElementById(x).style.opacity=0.5;
}
Though, to be honest, you could just use imgx
straight away; saving it into x
is a bit unnecessary.
Upvotes: 1
Reputation: 123387
premising that all handlers should never be defined inside markup (for the sake of separation between logic and contents) , try this
<img id="img1" src="img1.jpg" onmouseout="onhover(this)">
<img id="img2" src="img2.jpg" onmouseout="onhover(this)">
function onhover(img) {
img.style.opacity=0.5;
}
Upvotes: 3