views:

38

answers:

2

Hello.

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...

+3  A: 

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(); });
});
Nick Craver
Auch. I'm finally able to do something with this menu using jQuery (your selector works perfect and I'm able to change borders/backgrounds etc.), BUT the stop propagation stil doesn't work. What's wrong? <div id="boxLoaded"><div id="box-menu"><a href="#">Test</a></div></div> - still fades out the boxLoaded div ;/
fomicz
@fomicz - Are you using `.live()` or re-binding? Depending on order you may want to rebind to be safe, if not then the order of bindings can matter (they execute in the order bound), so you may need to switch to `.delegate()` and bind it first.
Nick Craver
The first method doesn't work, but the second does. Brilliant! You're here all the time, aren't U a some kind of a bot Nick? ;)
fomicz
@fomicz - shhhhhh, don't tell them!
Nick Craver
A: 

By calling e.preventDefault() you are only preventing the link from resuming its default event. After the link has been clicked on the containing div #boxLoaded still has its onclick() command. Instead of using e.preventDefault() try return false. I think that should do the same as preventDefault() in this case and also abort the commands that follow.

-- I cant comment on peoples posts yet but in response to Nick, 'thats cool, didn't realise there was a e.stopPropagation() function'

BIGDeutsch