Skip to content Skip to sidebar Skip to footer

Use One Function To Different Elements Javascript

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

Solution 1:

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

Solution 2:

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.

functiononhover(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.

Solution 3:

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

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

Post a Comment for "Use One Function To Different Elements Javascript"