Home > Net >  How to recognize which button is clicked
How to recognize which button is clicked

Time:01-10

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 > 
     <button >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?

CodePudding user response:

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);
 });

CodePudding user response:

Use querySelector instaid of getElementsByClassName

let openButton = document.querySelector('.common-button-class');
openButton.onclick = function() {
    //Your code here
};
  •  Tags:  
  • Related