dev.bashar
dev.bashar

Reputation: 181

Using jQuery basic functions

I have problem with call any jQuery function.

The load is working, but when I call another page nothing is working?

my code is:

js:

$(document).ready(function(){
    $("#content").load('page.php');

    $("#submenu").click(function () {
       alert('Hello');
    });
});

html:

<div id="content"></div>

page.php

<div id="submenu">
    <ul>
        <li><a href="#profile">profile</a></li>
        <li><a href="#logout">logout</a></li>
    </ul>
</div>

Upvotes: 1

Views: 95

Answers (1)

nnnnnn
nnnnnn

Reputation: 150050

I'm not sure what you mean by "when I call another page", but if you're trying to setup event handlers for elements within the content being loaded you need to wait until they have loaded - the .load() method is asynchronous, which means the code after it is executed immediately (i.e., without waiting for a response to the load) so to assign your .click() handler once it has completed move that part of your code into the .load() method's complete callback:

$(document).ready(function(){
    $("#content").load('page.php', function() {
       $("#submenu").click(function () {
          alert('Hello');
       });
    });
});

Alternatively you can use delegated event handling and bind the click handler to your container object:

$(document).ready(function(){
    $("#content").load('page.php');

    $("#content").delegate("#submenu", "click", function () {
       alert('Hello');
    });
});

See the .delegate() doco for more information, and note that if you are using the latest version of jQuery you should use the .on() method rather than .delegate(). (Or if you have a really old version of jQuery you'll need to use .live().)

Upvotes: 2

Related Questions