skip to Main Content

I am using wordpress for my blog posts – all posts are fetched on the same page and each post has button, I need to be able to recognise which button of which post was clicked.

I can do it only with hardcoded data, but I am unsuccessful with dynamic ones.

I tried to give a trigger button common class and then detect it in JS.

<div class="row"> 
     <button class="common-button-class">CLICK</button>
</div>

let openButton = document.getElementsByClassName(
    'common-button-class'
);


if (openButton != null) {
            document.querySelector('.common-button-class')
            .addEventListener('click', (event) => {
            // tried detect event id here unsuccessfully 
});
   }

Is there function of how to know which post is being triggered?

2

Answers


  1. Use querySelector instaid of getElementsByClassName

    let openButton = document.querySelector('.common-button-class');
    openButton.onclick = function() {
        //Your code here
    };
    
    Login or Signup to reply.
  2. you can use jquery in WordPress

    first add properties just like data-id and keep post id in it.
    then :

     $(document).on("click",".common-button-class", function () {
         var clickedBtnID = $(this).data('id'); 
         alert('you clicked on button #' + clickedBtnID);
     });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search