Search code examples
javascriptjqueryfunction-parameter

Javascript function(parameter), assign parameter to var


i am failing and i don't understand why, i hope some body could help me out.

<div id="anvil" onmouseover="show(anvil_info)">

what i want to do is when you hover over anvil it starts a function

function show(x){
x.style.backgroundImage = "image_"+x
}

My idea was to use the assigned parameter when the function was called to get the image, but if i now look try to use it it doesn't work. How do i use a variable assigned to the function?

This one still doens't work:

function show(x, y){
    x.style.zIndex = "1";
    x.style.opacity = "1";
    y.style.backgroundImage = "url('"+ y + "_hover')"
}
<div id="anvil" onmouseover="show(anvil_info, 'anvil')"></div>

Solution

  • new version :

     function show(elem, pIdToChange){
       document.getElementById(pIdToChange).style.backgroundImage = "url('"+ pIdToChange + "_hover')";
       // with color switch
       document.getElementById(pIdToChange).style.color = "red";
       elem.style.color = "";
    }
    <div id="anvil_info" onmouseover="show(this, 'anvil')" >Hello</div>
     <div id="anvil" onmouseover="show(this, 'anvil_info')">Goodbye</div>


    The best is to use onmouseover="show(this)"

    You'll get the element in your function, and then x.style.backgroundImage will work fine.

    function show(elem, pUrl){
      elem.style.backgroundImage = "url('"+ pUrl + "_hover')"
      alert(pUrl);
    }
    <div id="anvil" onmouseover="show(this, 'anvil')">hello</div>