0

on click event for a dynamically created item is something like this.

$('.static_parent').on('click','a', function () {

bur now Im trying to see if a element has a class, but its on a dynamic items. I tried a few variations of this but cant get it to work.

$('.input-group',this).hasClass('open') but surely the on will need to play a role in some way... or not?

I have multiple occurrences of .input-group and each has a dropdown where is class of open is added on click.

But what I dont get is how to test hasClass on the dynamic added dropdown.

Maybe a variation of this

$(document).on( 'click', '.button', function(e){
    var $button = $(this);
    var $menu = $button.closest('.menu');
    e.stopPropagation();

    // Close others-assumed you want all menus closed
    $('.menu').not($menu).removeClass('open'); 

    // Toggle target open/close
    $menu.toggleClass('open');

    $(document).on('click', function(e){
        //This function will only run when e.target isn't a button
        //Your $target.is($menu.find('button')) will always be false

        if( $menu.hasClass('open') ){
            $menu.removeClass('open');
        }
    });
});
morne
  • 3,552
  • 7
  • 35
  • 85
  • Your delegated event handler (as in the first snippet) is the correct code to use, you just need to ensure that the primary selector (`.static_parent` in your case) exists when the DOM initially loads. – Rory McCrossan Dec 18 '18 at 12:02
  • Yes, `.static_parent` is there on load, but I don fully understand your comment. Do you mean. Ho is this implemented for `hasClass`? – morne Dec 18 '18 at 12:08

0 Answers0