user3055501
user3055501

Reputation: 315

How To Call A Javascript Function On Page Load

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?

Upvotes: 0

Views: 12706

Answers (5)

Sergei Zahharenko
Sergei Zahharenko

Reputation: 1524

working just fine:

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

http://jsfiddle.net/acrashik/NEfR2/481/

Upvotes: 0

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18354

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

Upvotes: 0

Josh Beam
Josh Beam

Reputation: 19812

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

Upvotes: 1

kennebec
kennebec

Reputation: 104850

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

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

Upvotes: 2

Lucas Serafim
Lucas Serafim

Reputation: 3832

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

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

Upvotes: 0

Related Questions