10

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,825
  • 7
  • 37
  • 48
pixie123
  • 929
  • 3
  • 14
  • 27

4 Answers4

45

Find your DOM element, then call the click method:

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

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,293
  • 12
  • 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
  • 419
  • 1
  • 4
  • 19
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
  • 555
  • 4
  • 20