9

Here is my button code:

<button class="popup-trigger" data-modal="modal-1"></button>

How can i trigger the button click or even trigger the class popup-trigger with the data-modal modal-1?

would like to know in pure javascript, if you cant do it, then jquery. thanks

empiric
  • 7,665
  • 6
  • 39
  • 47
pixie123
  • 859
  • 3
  • 12
  • 22

4 Answers4

38

Find your DOM element, then call the click method:

document.getElementById("myButton").click(); 
bougiefever
  • 1,047
  • 10
  • 11
1

There can be various number of ways

<button class="popup-trigger" onclick="myFunction()" data-modal="modal-1"> </button>
<script>
function myFunction(){
 //do something here
}
</script>

Secondly using jQuery

<button id="my-btn" class="popup-trigger" data-modal="modal-1"> </button>
<script>
$("#my-btn").click(function(){
 //do something here
 })
</script>
geekbro
  • 1,197
  • 10
  • 13
0

In pure JavaScript:

// Since there can be multiple elements with the class "popup-trigger", it returns an array. Putting the [0] will call the first button with the class "popup-trigger".
var myButton = document.getElementsByClassName("popup-trigger")[0];
// If you wanted to check clicks on ALL buttons with the class, remove the [0] at the end.

// Check for clicks on the button
myButton.onclick = function(e) {
  alert(e.target.getAttribute("data-modal"));
}
<button class="popup-trigger" data-modal="modal-1">Button</button>

I inserted comments explaining it. Let me know if you have any questions.

Jamsheed Mistri
  • 379
  • 1
  • 3
  • 17
0

What about this...

let button = document.querySelectorAll('button.popup-trigger')

function myFunction(){
    alert("Button pressed")
}

button.forEach(function(element){
    if (element.dataset.modal == "modal-1"){
   element.addEventListener("click", myFunction, false);
    }
})
<button class="popup-trigger" data-modal="modal-1">Button 1</button>
<button class="popup-trigger" data-modal="modal-2">Button 2</button>
<button class="popup-trigger" data-modal="modal-3">Button 3</button>
Neil Docherty
  • 565
  • 4
  • 19