Monset Monset - 2 months ago 6
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

onload
function, which will automatically take care of the image's source and
mouseover/out
functions.

The HTML looks like this:

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


and the JS function
imgButton
looks like this:

function imgButton(e){
window.alert("asdasdad");
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
<head>
and setting
src
to none
src=""
in the
<img>
. I'm using Firefox, but it doesn't work in Edge either.

Question is: how do I fire
onload
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
"images/def/..."
and all images for when the mouse is over the
img
are in
"images/mo/..."
.

Answer

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 = thisImage.data('regular');
    var hover = thisImage.data('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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img data-regular="https://placehold.it/350x150" data-hover="https://placehold.it/450x200" />

Also on JSFiddle.

Comments