Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Only Image Hover

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!

like image 609
Tania Rascia Avatar asked Aug 31 '26 17:08

Tania Rascia


1 Answers

var image = document.getElementById("hover-example");
image.onmouseover = function() {  image.src = "image-hover.png"; }
image.onmouseout = function() {  image.src = "image.png"; }
like image 109
Duncan Thacker Avatar answered Sep 03 '26 08:09

Duncan Thacker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!