Please house i have a code and for some reasons the click event won’t work if append is being used, but if written directly into the html it works.
What could be the reason. am using jQuery.
//html
<!-- HTML code -->
<div class="preview">
<!-- HTML code will be added dynamically -->
</div>
<button class='jump'>jump</button>
// JavaScript code using jQuery
$('.jump').on('click', function(){
const newElement = "<p class='clickable'>Click me</p>";
$('.preview').append(newElement);
});
$('.clickable').on('click', function() {
console.log('Element clicked');
$(this).remove();
});
The idea is to add a paragraph with a class called clickable anytime the jump button is clicked .
Then if the dynamically appended paragraph with the clickable class is clicked it should remove the button.
but the clickable onclick is not working, but if i write the
<p class='clickable'> Click me</p>
,~~~
inside the html directly the clickable onclick function will work, but appending seems like is not working even when i can see the element in browser source code
Have a read through that, but the basics of it are: You’re trying to attach an event listener to $('.clickable') before any of the clickable class things are in the DOM. So the browser gets told “attach this event listener to all the clickables”, it looks, sees none, and says “I’m done.”
What you need to do is attach the event listener to the parent div, and delegate it from that parent to the .clickable elements beneath that parent. That way, the parent reacts to the event, and hands it to the child to act on.