Search code examples
javascripthtmlonmouseoveronmouseout

inserting an image on mouse over and onmouse out


I have an image inside a div which im trying to change when the mouse is over then revert when the mouse is out. However I am having difficulties inserting the image into the div on mouse out. Is the a particular way to go about this or an alternative message. The issues seems to be with the placement of slashes in the HTML insertion.

  <div class='myImage' onmouseout='this.innerHTML = '<img src='./images/myImage.jpg' />' onmouseover='this.innerHTML = \"\"; this.style.backgroundColor = \"#1D4088\"' style='height:100px; width:100px'><image src='./images/myImage.jpg'></div>

Solution

  • I think your double and single quotes are a bit conflicting, try putting the javascript into a function instead

    <div class="myImage" onmouseout="toggle(this,'1')" onmouseover="toggle(this,'2')" style="height:100px; width:100px"><image src="./images/myImage.jpg"></div>
    

    And the javascript

    function toggle(e,a) {
        if(a=='2') {
            e.innerHTML = '';
            e.style.backgroundColor = '#1D4088';
        } else {
            e.innerHTML = '<img src="./images/myImage.jpg" />';
            e.style.backgroundColor = '';
        }
    }