0

I've made a small page that just has this as the HTML:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">

<title>hi</title>

<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<link type="text/css" href="js/jquery-ui-1.9.1.custom/css/black-tie/jquery-ui-1.9.1.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="js/jquery-ui-1.9.1.custom/js/jquery-ui-1.9.1.custom.js"></script>

<link type="text/css" href="css/main.css" rel="Stylesheet" />
<script src="js/main.js"></script>

<script>
    $(main());
/* or $(document).ready(main()); */
</script>
</head>
<body>
<div id="loginDiv" class="popupDiv">
    <div id="usernameDiv">
        <label for="username">username</label>
        <input type="text" id="username"/>
    </div>
    <div id="passwordDiv">
        <label for="password">Password</label>
        <input type="password" id="password"/>
    </div>
</div>

<div id="introDiv">
    <div class="headerDiv">
        <button id="loginButton">Login</button>
    </div>
</div>
</body>
</html>

And then I have my main.js:

function main()
{
    var $loginButton = $('#loginButton');
    var $loginDiv = $('#loginDiv');

    $loginDiv.dialog({ autoOpen: false });

    $loginButton.click(function() {
        $loginDiv.dialog("open");
        //alert('sfsdf');
    });
}

I can trigger alerts, but selectors will not return any elements if the .ready() handler is specified in the head.

I have tried moving it to the end of the body tag and everything works fine. According to the JQuery docs, the entire DOM and all images and resources are supposed to be loaded before the handler gets called. What gives?

  • Firefox 16.0.2 on Linux x86
  • JQuery 1.8.2
  • JQuery UI 1.9.2 (not really used for the purposes here)
Nick
  • 4,901
  • 40
  • 61
  • Same idea: http://stackoverflow.com/questions/10947786/difference-between-clickhandler-and-clickhandler , http://stackoverflow.com/questions/7102413/why-does-click-event-handler-fire-immediately-upon-page-load (and many more) –  Nov 16 '12 at 02:21
  • Yup, but had I known that was the problem in the first place, I would have found those. – Nick Nov 16 '12 at 14:57

1 Answers1

7

Because you are calling your function!

$(main());   <--() means run it

You want to assign a reference to it

$(main);  <-- no ()!
epascarello
  • 204,599
  • 20
  • 195
  • 236