-1

I have an issue with the replaced HTML elements.

I am using jquery on bookmark svg icon to replace it with filled/unfilled bookmark on some div elements.

The code below works well on html elements that are already in my html file however the click event does not fire on the replaced SVG element.

  bookmark_Unfilled = ' <svg xmlns="http://www.w3.org/2000/svg"  width="16" height="16" fill="blue" class="bi bi-bookmark" viewBox="0 0 16 16"> <path d="M2 2a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v13.5a.5.5 0 0 1-.777.416L8 13.101l-5.223 2.815A.5.5 0 0 1 2 15.5V2zm2-1a1 1 0 0 0-1 1v12.566l4.723-2.482a.5.5 0 0 1 .554 0L13 14.566V2a1 1 0 0 0-1-1H4z"/></svg> ';
     bookmark_Filled = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="blue" class="bi bi-bookmark-fill" viewBox="0 0 16 16"> <path d="M2 2v13.5a.5.5 0 0 0 .74.439L8 13.069l5.26 2.87A.5.5 0 0 0 14 15.5V2a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2z"/> </svg>' ;
   $( " .bi-bookmark" ).click(function() {
    
    
//  console.log($(this));
//  console.log($(this)[0]['classList'][1]);
    $(this).replaceWith(bookmark_Filled);
  });


 
 $( ".bi-bookmark-fill" ).click(function() {
  
  
     $(this).replaceWith(bookmark_Unfilled);
 });

I might missing something could you please help me out. THere are several bookmarks in my html file I always want to change the value of the bookmark that was clicked.

  • Selectors and event handlers specified at page load will only match elements which exist at page load. You are adding new elements *after* page load, and your event listeners will not match them. You need to delegate your handlers to an element that exists at load, and filter to match only your target elements. See https://stackoverflow.com/questions/1359018/how-do-i-attach-events-to-dynamic-html-elements-with-jquery – Don't Panic Apr 01 '23 at 14:30

1 Answers1

1

You can use the document on click syntax to trigger click on dynamic elements.

$(document).on("click", ".bi-bookmark", function() {
// your code here
});

$(document).on("click", ".bi-bookmark-fill", function() {
// your code here
});

I would also suggest another approach. Have both of the SVG's in one container. Show one by default. On click show other SVG by toggling a class. That would be much simpler. This way you don't have to replace content.

Shreyas Kumar
  • 164
  • 1
  • 6
  • I edited the selector in your code to work it after the replace. But I strongly agree with you that it should be in a container and replacing the content, not full element. – Martin Ille Apr 01 '23 at 14:08
  • Thanks @MartinIlle. I assumed they would add another similar function for the other click. Since the action is different I have seperated them into two click functions in my recent edit. – Shreyas Kumar Apr 01 '23 at 14:19
  • Good idea, you're right. The separated clicks is better solution in this case. – Martin Ille Apr 01 '23 at 14:26