4

The .click() event is firing if the menu is outside the id="content" (static HTML) but not working when the menu is inside the id="content" (dynamic HTML using .load()).

Click function:

$(document).ready(function () {
    $("a.type").click(function () {
        var type = $(this).data("id");
        $('#content').load("content.php?" + type);
    });
});

Menu link on header (click event works here):

<li><a data-id="1" class="type">Cars</a></li>
<li><a data-id="2" class="type">Houses</a></li>

.load() fills this (click event not working here):

<div id="content"></div>
2
  • Can you post a JSFiddle to show an example? Commented Dec 21, 2011 at 22:51
  • The events have already been bound before the data is loaded through AJAX. Jake Feasel's answer should fix it, but just thought you might want to know why it's happening. Commented Dec 21, 2011 at 22:53

1 Answer 1

8

Change from

$("a.type").click(function 

to

$("a.type").live('click', function 

Or, rather than live, you could also use $(document).on("click", "a.type", function(){}) if you are using jQuery 1.7+.

Sign up to request clarification or add additional context in comments.

7 Comments

live is deprecated in jQuery 1.7+ and should not be used (use on instead). Even before 1.7, delegate should be used instead.
I think that the docs now recommend to use on (jquery 1.7+) or delegate (previous versions) rather than live.
@JakeFeasel - As mentioned, even before 1.7 live is not recommended. Use delegate instead.
Also note that your on example won't solve the problem. It's equivalent to .click. You would need to bind the event handler to an ancestor element, and use the 2nd argument of on as a selector (in this case a.type). The same applies for delegate.
I've fixed it to reflect your point, @JamesAllardice. Thanks for the tip.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.