简体   繁体   中英

Toggle div except on anchor click

I would like to toggle my div on clicking anywhere on the parent div except when an anchor element is clicked. So for example, if I click the first text in my example, I would like it to toggle but on the second text in my example, I don't want it to toggle.

JSFiddle

I have tried using !key.relatedTarget.tagName == 'a' but I keep getting undefined

You should checking event target:

function show_description(key) {
  if( !$( event.target ).is( "a" ) )
    {
        $('#' + key + '_description').slideToggle(100);
    }
}

JSFiddle

See the above answer.

For a JQuery way of doing it;

$(document).ready(function(){
  $('.panel').on('click', function(e){
      if(e.target.id != 'test_description'){
        $('.description').toggle();
      }
  });
})

jsfiddle

Or specifically for an A-element;

$(document).ready(function(){
  $('.panel').on('click', function(e){
        var target = $( e.target );
        if ( !target.is("a") ) {
            $(this).find('.description').toggle();
        }
  });
})

jsfiddle

For javascript only:

        if ( target.get(0).tagName.toLowerCase() != 'a' ) {

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