Search code examples
javascriptjqueryeventtriggerdynamic-content

Using trigger with dynamic content


I'm dynamically loading content which includes a series of buttons. I want to trigger a click on a second button when the first button is pressed, however the trigger event never fires.

jQuery

$(document).on('click', '.main-button', function() {
    var self = $(this).attr('class').split(' ')[0];
    $('button.' + self + '.product-id').trigger('click');
});

HTML

<div class="button-wrap">
    <button class="b-1 main-button"></button>
    <button class="b-1 product-id"></button>
</div>
<div class="button-wrap">
    <button class="b-2 main-button"></button>
    <button class="b-2 product-id"></button>
</div>

Solution

  • You don't need the dot in the actual class name, only in the css selector. Instead of class="b-1 .main-button" you want: class="b-1 main-button". The same for the other classes.

    Note: you also have to have an onclick handler for the product buttons, otherwise you won't see the clicking.

    $(document).on('click', '.main-button', function() {
        var self = $(this).attr('class').split(' ')[0];
        $('button.' + self + '.product-id').trigger('click');
    });
    
    $(document).on('click', '.product-id', function() {
      var klass = $(this).attr('class');
      alert(klass + " prod button triggered");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="button-wrap">
        <button class="b-1 main-button">B1 main</button>
        <button class="b-1 product-id">B1 prod</button>
    </div>
    <div class="button-wrap">
        <button class="b-2 main-button">B2 main</button>
        <button class="b-2 product-id">B2 prod</button>
    </div>