Rollover Effect: Change Picture with Mousehover

907 views Asked by At

I'm trying to create a hover that will change the picture. A lot of tutorials tell me to try onmouseover and onmouseout. But Brackets (the program I use to code) isn't able to find the second picture called "test2.png". Does anybody know how I could handle the issue, preferably using only HTML.

Here are the tutorials I watched that show what I would like to achieve:

https://www.youtube.com/watch?v=qtpa_r1ILjo

https://www.youtube.com/watch?v=y4RJDUI7M8Y

<!DOCTYPE html>
<html>
    <head>
        <title>Portfolio V1</title>

        <link rel="stylesheet" type="text/css" href="main.css"/>
        <script type="text/javascript"></script>
    </head>
    <body>
        <img src="images/test1.png" onmouseover="this.src=images/test2.png" onmouseout="this.src='test1.png'" >
    </body>
</html>    
3

There are 3 answers

5
Dekel On BEST ANSWER
  1. You need to make sure that both images exists and in the correct folder.
  2. Make sure that the name is exactly the same as you write it in your code.
  3. One of the problems you had is that you didn't wrap the name of the image (in onmouseover with quotes: 'images/test2.png').
  4. In the onmouseout you set the image to test1.png instead of images/test1.png. Is it intended?

Here is a working example:

<img src="https://dummyimage.com/600x400/000/fff" onmouseover="this.src='https://dummyimage.com/600x400/f00/fff'" onmouseout="this.src='https://dummyimage.com/600x400/000/fff'" >

3
CWBudde On

You have to use JavaScript to make this work. It won't work inplace like you have tried.

EDIT: It does work inplace, but you have missed the single quotes.

In the onmouseover attribute you should refer to a JavaScript function. Have a look at this question about onmouseover for more information.

For example you could use something like this:

<img src="images/test1.png" onmouseover="MouseOver(this)" onmouseout="="MouseOut(this)" >

Now you refer to event handlers for the onmouseover and onmouseout event. However, these event handlers still need to get defined in a javascript snippet. This could get embedded in the element like this:

function MouseOver(myimg) {
  myimg.src="images/test2.png";
}

function MouseOut(myimg) {
  myimg.src="images/test1.png";
}
0
KolaCaine On

I made an example with background-color, but the principle is here.

You can check the code :

const div = document.querySelector('div');

window.addEventListener('mouseover', () => {
 div.style.background = 'red'
})
div {
  width: 100px;
  height: 100px;
  opacity: 1;
  background-color: green;
  transition: 3s;
}
<div></div>