change an image onload

I have a simple webpage with an image in a div on the homepage and would like to use javascript to change the image for an alternative image after the page has loaded (only once) using a slow fade, i am currently using an animated gif to do this but would prefer to use javascript.

I have limited javascript skills.

thanks

Answers


I'm assuming that you won't use jQuery so i've created simple js eample which fades out one image and fades in other after page is loaded. You can check the example here http://jsfiddle.net/rJzPV/7/

function fadeOut(elem, time, callbackFn) {
    var startOpacity = elem.style.opacity || 1;
    elem.style.opacity = startOpacity;

    (function go() {
        elem.style.opacity -= startOpacity / (time / 100);

        // for IE
        elem.style.filter = 'alpha(opacity=' + elem.style.opacity * 100 + ')';

        if (elem.style.opacity > 0.11)
            setTimeout(go, 100);
        else {
            elem.style.display = 'none';
            if (callbackFn)
                callbackFn();
        }
    })();
}

function fadeIn(elem, time) {
    var startOpacity = 0.1;
    elem.style.opacity = startOpacity;
    elem.style.display = "";
    (function go() {
        elem.style.opacity -= -startOpacity / (time / 1000);

        // for IE
        elem.style.filter = 'alpha(opacity=' + elem.style.opacity * 100 + ')';

        if (elem.style.opacity < 1)
            setTimeout(go, 100);
    })();
}

window.addEvent('load', function () {
    function changePicture() {
        var _myImg = document.getElementById("myImage");
        _myImg.src = "http://www.google.com/logos/2012/klimt12-hp.jpg";
        fadeIn(_myImg, 1000);
    }

    var _myImg = document.getElementById("myImage");
    fadeOut(_myImg, 1000, changePicture);

});

Need Your Help

EntityValidationException is thrown when saving my entity

entity-framework asp.net-mvc-4 c#-4.0

I got this message when debugged in catch (Exception e). When User fill in all the information, Address and Payment View will get the SalesOrderID and redirect to Complete View. But it didn't show ...

Thread suspends itself and another one resumes it afterwards - sometimes second event happens first

multithreading parallel-processing synchronization

I have two threads; thread 2 provides necessary data for thread 1 and can start working on another piece of data in parallel with thread 1 processing it, but won't move onto the next piece if threa...