Miguel Garrido Miguel Garrido - 1 year ago 62
Javascript Question

Why jQuery loses 'event' (click) when some content has been loaded?

I am trying to load content with this next script when I select pages on the sidebar. This script works without problems:

if(Modernizr.history) {
var newHash = "",
$wrapperTag = $("#main-content"),
contentTag = '#main-content-inside',
activeClass = 'active';

$("#sidebar").delegate("a", "click", function() {
_link = $(this).attr("href");
history.pushState(null, null, _link);

return false;

function loadContent(href){

$wrapperTag.load(href + " "+contentTag+" ", function(response, status, xhr) {

$("#sidebar a").removeClass(activeClass);
$('#sidebar a[href$="'+href+'"]').addClass(activeClass);




This script works without probs and my HTML template looks something like this:

HTML Template

<div id="sidebar">
<ul class="ul-vert">
<li><a href="page1.html">Page 1</a></li>
<li><a href="page2.html">Page 2</a></li>
<li><a href="pageN.html">Page N</a></li>

<div id="main-content">
<div id="main-content-inside">
<p id="menu">Show / Hide Sidebar</p>
<div class="text desc">(Content)</div>

I've got a tag which is p#menu as an option to display or hide the sidebar. This works just until I load any page then I lose the click event.

So basically my question is:

Why jQuery losses the event after change the content?
I could solve this adding again again p#menu on loadContent functions, but I want to understand how jQuery works.


Answer Source
$('.fatherDiv').on('click','.childDiv', {} ,function(e){
 //insert your code here

This will bind the event handlers to the DOM selector elements not only now, but also in future (selectors added to DOM after the bindings). Now the click event fires even the specific selectors are added or replaced with new DOM elements.

Read here for further info:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download