1

I come across with this problem on javascript where element is yet to be created or to be created in the future and there this event to be bind for that element, in jQuery, I can do

$(function(){
$(document).on('click','.mybtn',function(){
  alert('button: '+$(this).index());
});

$('#create-sample-btn').click(function(){
$('#btn-container').append('<button class="mybtn">Button</button>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="btn-container"></div>
<button id="create-sample-btn">Create Sample Btn</button>

Any help, ideas on how to achieve that in pure javascript?

Whats the equivalent of $(document).on(.. in native javascript?

Juliver Galleto
  • 7,927
  • 19
  • 69
  • 138

1 Answers1

1

You can use event Delegation, attach the event on the parent component and when the event occurs on the element, it will bubble up and will be captured by the parent.