1

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')">

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

@Alnitak Honestly I didn't make the connection that the ID being passed to the function was the ID of the element triggering the function. In that case, this would be the better option.
well, it is, but only if you actually pass it as a parameter (for DOM0 inline handlers). For proper DOM3 (and jQuery) it's implicit.
0

I have created codebin for you please check using below link.

http://codebins.com/codes/home/4ldqpcc

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.