简体   繁体   中英

run a jquery function onload and focus

I have a function :

function skillbar() {
    $('.skillbar').each(function(){
        var percent = $(this).attr('data-percent');
        $(this).find('.skillbar-bar').delay(400).animate({width:percent},1500);
    });
}

I want this function to be executed when the page is loaded. so I run it like this :

$(window).load(function(){
    skillbar();
});

but I also want this function to be run only when browser tab is focused. I tried this:

$(window).load(function(){
    $(window).focus(function(){
        skillbar();
    });
});

The problem is that, when I use .focus(); when page is loaded, I have to switch browser tab once, and then it works. It means I have to focus on window onload, but what if someone is on another browser tab ?

demo http://jsfiddle.net/sem847un/1/

You need $(document).ready(function(){ This will initiate the function on load

$(document).ready(function(){
skillbar();
function skillbar() {
    $('.skillbar').each(function(){
        var percent = $(this).attr('data-percent');
        $(this).find('.skillbar-bar').delay(400).animate({width:percent},1500);
    });
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM