Monset Monset - 11 months ago 42
HTML Question

onload not working in <img> element

I don't understand why this function doesn't fire. I want to declare an image in HTML with a single

function, which will automatically take care of the image's source and

The HTML looks like this:

<img id="menuBtnNovo" onload="imgButton(this)"/>

and the JS function
looks like this:

function imgButton(e){
e.src="images/def/" + e.Id + ".png";
e.onmouseover= function(){ *change image here*}
e.onmouseout= function(){ *change image back here*}

Now, not even the alert pops up, and I don't know why. I tried putting script in
and setting
to none
in the
. I'm using Firefox, but it doesn't work in Edge either.

Question is: how do I fire
function on an image element?

Also, if you have any idea of your own way of implementing this behaviour of automatically loading certain images (that would actually be buttons/links), feel free to share it. I'm new to JS but not to programming.

As you might see, all images are in
and all images for when the mouse is over the
are in

Answer Source

I always try and let browser do image replacements, but if you have to use script, than you can do something like this on DOM ready, or window load event:

$('img[data-regular]').each(function(i) {
    var thisImage = $(this);
    var regular ='regular');
    var hover ='hover');
    thisImage.attr('src', regular);
    /* Preload image for hover */
    $('<img/>')[0].src = hover;
    /* Set events */
    thisImage.on('mouseenter', function(e) {
        thisImage.attr('src', hover);
    }).on('mouseleave', function(e) {
        thisImage.attr('src', regular);
<script src=""></script>
<img data-regular="" data-hover="" />

Also on JSFiddle.