15

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

1

4 Answers 4

55

Find your DOM element, then call the click method:

document.getElementById("myButton").click(); 
Sign up to request clarification or add additional context in comments.

Comments

3

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>

Comments

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.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.