Search code examples
jqueryevent-bubbling

Preventing bubbling after loading?


I've a huge problem.

I'm having a div named "#box" that loads external content after clicking links in it:

$("#box a").click(

 function(e)
 { 
 e.preventDefault(); 
 var hash = this.parentNode.hash;
    $("#boxLoaded").load('boxFiles/'+ hash.substring(1) +'.html');
    $("#box").fadeOut(100);  
    $("#boxLoaded").fadeIn(200);     
 });  

Easy so far :)

When somebody clicks anywhere in "#boxLoaded" it disappears and loads box again, so it looks like in the beginning:

$("#boxLoaded").click(
    function()
    {  
        $("#boxLoaded").fadeOut(200);
        $("#box").show(); 
 });  

The problem is I have a menu named "box-menu" in loaded files (inside of #boxLoaded) and when somebody clicks them - the code above is being executed (fading out #BoxLoaded and showing #Box).

I want to prevent it from happening, but:

$("#box-menu").click(
    function(e)
    {  
        e.preventDefault() 
 });  

What to do? It works fine, when I'm not loading() these files...


Solution

  • You just need to switch to .live() and stop the bubbling via event.stopPropagation() here:

    $("#box-menu").live("click", function(e) {
      e.stopPropagation();
    });  
    

    Alternatively, you can re-bind then loading, changing this:

    $("#boxLoaded").load('boxFiles/'+ hash.substring(1) +'.html');
    

    To this:

    $("#boxLoaded").load('boxFiles/'+ hash.substring(1) +'.html', function() {
      $("#box-menu").click(function(e) { e.stopPropagation(); });
    });