3

This is purely for learning purposes; I know that CSS would be the preferred method for this situation.

I know that in JavaScript, you can use inline event handling to hover over an image, like so:

<img src="image.png" onMouseover="src='image2.png'" onMouseout="src='image.png'">

And I know you can install jQuery in your site, and do the following code or similar:

HTML:

<img src="image.png" id="image-hover">

jQuery:

$(document).ready(function() {
        $( "#hover-example" ).mouseover(function(){
            $(this).attr("src", "image-hover.png");
        });

        $( "#hover-example" ).mouseout(function(){
            $(this).attr("src", "image.png");
        });
    });

I was wondering how one would use JavaScript-only to produce that output, but use an external script instead of inline event handling. I've tried browsing through various Stack Overflow and Google searches, but mostly they lead to using jQuery instead. Could it be that complicated to apply that simple inline JavaScript to an external script?

Thanks!

Tania Rascia
  • 1,563
  • 17
  • 35

3 Answers3

3

Pretty much the same way

var img = document.getElementById('image-hover');

img.addEventListener('mouseenter', function() {
    this.src = 'image-hover.png';
}, false);

img.addEventListener('mouseleave', function() {
    this.src = 'image.png';
}, false);
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thanks a lot! I tested that out and it worked. It has a few elements I haven't learned yet, so now I know to look them up. – Tania Rascia Jun 17 '15 at 06:17
2
var image = document.getElementById("hover-example");
image.onmouseover = function() {  image.src = "image-hover.png"; }
image.onmouseout = function() {  image.src = "image.png"; }
Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20
  • 1
    Thank you so much! This was the simplest and easiest answer for me to understand. I would upvote you, but I'm still too new. I'm not entirely certain why my post got downvoted; I know it's a stupidly simple question, but I learned something and maybe someone else will. – Tania Rascia Jun 17 '15 at 06:14
1

Since you're interested in a vanilla JavaScript implementation, take a look at the documentation for the mouseover event.

You can achieve your desired result by doing something like this:

var img = document.getElementById('image-hover');

img.addEventListener('mouseenter', function() {
    this.src = 'image-hover.png';
}, false);

img.addEventListener('mouseleave', function() {
    this.src = 'image.png';
}, false);
Danny Delott
  • 6,756
  • 3
  • 33
  • 57