Search code examples
jqueryimagebackgroundfade

trigger jQuery on load


I would like to have a fade between back ground images on my site. I've found out how to trigger a fade with a click but I don't know how I can launch it automatically. I came up with this (JavaScript code):

    $('div').click(function (e) {
       $(this).parent().append('<div style="position:absolute; top: 25px; left: 25px; z-index: 1;" class="google"></div>');
       $(this).fadeOut('slow');
    });


function fade() {
        $(this).parent().append('<div style="position:absolute; top: 25px; left: 25px; z-index: 1;" class="google"></div>');
        $(this).fadeOut('slow');
};

see at: http://jsfiddle.net/bbqunfhu/1/ the first function is triggered on click and the second one should be called in the "onload" event of the page. I would like to trigger the fade when the page gets loaded after let's say 10 seconds, I will want to have multiple images it goes through, how can I achieve that effect?


Solution

  • You need make correct your jQuery reference/selector in a less relative terms. For example, you can call this in the load instead:

    function fade() {
            $('div.jquery').parent().append('<div style="position:absolute; top: 25px; left: 25px; z-index: 1;" class="google"></div>');
            $('div.jquery').fadeOut('slow');
    };
    
    fade();
    

    js.fiddle here.

    You original code defined the fade() function but didn't call it. That's why the fade did not happen. You need to somehow call it.

    In addition $(this).parent() could mean different things inside div is click callback and in a function.