最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How To Call A Javascript Function On Page Load - Stack Overflow

programmeradmin3浏览0评论

I have this little snippet of code in script tags, along with some functions:

window.onload = function()
    {
        if (window.location.hash === 'open')
        {
            $("#signinform").css("display", "block");
            $(".blackout").css("display", "block");
        }
    }

It's not working and I'm pretty sure its just because of a syntax error. However, I can't find it. The function is intended to be called when the page is loaded. Can you guys find the problem?

I have this little snippet of code in script tags, along with some functions:

window.onload = function()
    {
        if (window.location.hash === 'open')
        {
            $("#signinform").css("display", "block");
            $(".blackout").css("display", "block");
        }
    }

It's not working and I'm pretty sure its just because of a syntax error. However, I can't find it. The function is intended to be called when the page is loaded. Can you guys find the problem?

Share Improve this question asked Jan 5, 2014 at 2:38 user3055501user3055501 3152 gold badges5 silver badges7 bronze badges 2
  • You are already using jQuery, so is there any reason you aren't using $(document).ready(function() { /* Your code here */ }); ? – Katsuyuki Omuro Commented Jan 5, 2014 at 2:41
  • The url is ".../home.php#open". Is this correct? – user3055501 Commented Jan 5, 2014 at 2:42
Add a ment  | 

5 Answers 5

Reset to default 2

window.location.hash includes the hash mark ('#').

It will never match 'open', or any string without the hashtag.

Try this:

if (window.location.hash === '#open')

The hash member of window.location will return the # sign, plus whatever string follows it.

You can detect this behavior by typing console.log(window.location.hash) into your console.

Additionally, since you are already using jQuery, you could potentially stick with:

$(function() {

instead of

window.onload

Are you using jquery right? Try using .ready(); http://api.jquery./ready/

A good way to write javascript is put all your javascript code on end of your page, before </body>

As you are using jquery, you can do:

$(document).ready(function(){
    if (window.location.hash === '#open')  //Inlude hash here!
    {
        $("#signinform").css("display", "block");
        $(".blackout").css("display", "block");
    }
});

window.location also works, but it takes much longer, for example if you have big images in your page, it will wait until all are loaded. $(document).ready doesn't have this problem.

Cheers

working just fine:

function loaded() {
    if (window.location.hash == '#open') alert('ok');
}
window.location.hash = 'open'
window.onload = loaded;

http://jsfiddle/acrashik/NEfR2/481/

发布评论

评论列表(0)

  1. 暂无评论