Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

        loadContent(_link);
        return false;
    });

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

                        $("#sidebar a").removeClass(activeClass);
                        $('#sidebar a[href$="'+href+'"]').addClass(activeClass);
                        
                        $("#menu").bind('click',function(){
                            $(this).showSidebar();
                        });

                    });
        
    }

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

HTML Template

<div id="sidebar">
    <nav>
        <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>
        </ul>
    </nav>
 </div>

 <div id="main-content">
     <div id="main-content-inside">
         <p id="menu">Show / Hide Sidebar</p>
        <div class="text desc">(Content)</div>  
     </div>
 </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.

Thanks!

like image 749
Miguel Garrido Avatar asked Jun 13 '13 04:06

Miguel Garrido


People also ask

Why on click is not working jQuery?

jQuery click not working at the time page loading, jQuery Onclick Method is tried to an element or selector. As a result, the binding will fail if the element we wish to click isn't present when the page is ready.

Does jQuery work on dynamic content?

With jQuery, what happens is it bind event listeners on each DOM element inline and not on classes or ids. So when the binding method is called, events are bonded on the DOM loaded. To bind event on dynamically loaded DOM, we bind the event to the nearest static parent and give the element we want to bind event.

Does jQuery empty Remove event handlers?

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

How do jQuery events work?

These events are often triggered by the end user's interaction with the page, such as when text is entered into a form element or the mouse pointer is moved. In some cases, such as the page load and unload events, the browser itself will trigger the event.


1 Answers

$('.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:
http://blog.revathskumar.com/2013/10/jquery-on-avoid-losing-event-binding-for-ajaxed-contents.html

like image 70
Gal Margalit Avatar answered Jan 03 '23 21:01

Gal Margalit