简体   繁体   中英

Clickable div with unclickable elements.

http://codepen.io/anon/pen/zxoYBN

I wrote this small bit to illustrate my issue, but essentially I have a linkbutton on a div that toggles another div via click, but I want the linkbutton to not toggle, and be exempt from the click event.

I also cannot use the cursor-event:none; trick because I have to make this work with IE.

Here's the javascript:

$(function(){
  $('#expandingHeader').click(function(){
    $('#expandingContent').slideToggle();
  })
})

I expect that clicking a div that should be on top of #expandingHeader shouldn't cause the clickevent, but it does. Any help would be appreciated.

$(function(){
  $('#expandingHeader').click(function(){
    $('#expandingContent').slideToggle();
  })
  $('#expandingHeader>a').click(function(e){
    e.stopPropagation();
  })
})

Use javascript to prevent the default action of the href.

$('#no-toggle-link').click(function(){
    alert("You can redirect the user from here instead of an alert!");
    return(false);
}) 

Check my example:
http://codepen.io/anon/pen/qEqBaP

you can do the checking on the event object

$(function(){
 $('#expandingHeader').click(function(e){
   if (e.target.tagName === 'A') { // simply call the return when found the target is action link <a>
     return;
   }
 $('#expandingContent').slideToggle();
})
})

Demo on codepen ( http://codepen.io/anon/pen/vEyYyr )

Without any additional event listeners.
You can check what kind of element was clicked (which is accessible via event.target ) and if it was a link, then you do not toggle the content.

$(function() {
  $('#expandingHeader').click(function(event) {
    // Check if we clicked a link, and if so, do not proceed.
    // Check only immediate children of the header.
    if (event.target.parentNode === event.currentTarget
        && event.target.nodeName === 'A') {
        return;
    }

    $('#expandingContent').slideToggle();
  })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM