Search code examples
javascriptjqueryhoverlive

How do I disable the onclick of parent when live child is clicked?


So typically I just use stopPropegation when I need to prevent the default action of the parent when a child is clicked. However, this doesn't seem to be work with live elements. So I had the idea to temporarily remove the onclick attribute of the parent when the child is hovered over. I seem to be able to remove it just fine, but I cannot seem to be add it back to the element... this is what I came up with...

$('body').delegate('.button', 'mouseenter mouseout', function(e){
        if(e.type=='mouseenter'){
          var inside = $(this).parents('.post').attr('onclick');
          $(this).parents('.post').attr('onclick','');
        }else if(e.type=='mouseout'){
          $(this).parents('.post').attr('onclick', inside);
        }
    })

So this will remove the element successfully, however the attempt to add it back is always unsuccessful... it just comes up empty. Can anyone give me a hand here? I'm completely stuck. I'd also be happy with alternative method to achieving the same result. Thank you.


Solution

  • try this http://jsfiddle.net/kDuNU/4/:

    $('div').live('click', function(event) {
        if ($(event.target).hasClass('button'))
           return;
        alert('hello');
    });
    
    $('.a-span').live('click', function (event) {
        alert($(this).text());
    });
    $('div').append('<span class="a-span button">another</span>');
    
    <div> hello <br/>
        <span class="a-span">world</span>
    </div>