Appending HTML code using JavaScript seems not to work properly

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.

Check your quotes. They’re all over the shop.

Once you’ve done that, the javascript console will start yelling at you about that close parenthesis, too.

Thanks alot but thats not actually the issue, it was a type i will correct now

remove the word “function”, or remove the arrow. big arrow notation is just (parameters) => {
regular function decalaration would be function() {

cant mix the two.

okay thanks will remove it now

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

Right, so now we’ve gotten past the syntax errors, we come to the logical error.

What you need is called Event Delegation.

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.

great, will look up the guide you shown me on how to attach and delegate event listening and then will be back to give you feedback.

Thanks alot for understanding the problem in the first instance

Thank you very much @m_hutley
the solution worked, using a parent div then i

//added 
<li>clickme</li>

//then added
$('. preview').on('click, 'li', function (){

// my other functions or remove goes here

});
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.