Back

Technologies:

javascriptjavascript
avatar
Tolerim
a day ago

How can a pop up message be triggered upon clicking a button using a class name?

As a solution to display a pop-up message upon clicking a button with the class="send:after", the following JavaScript code can be used:

<script type="text/javascript">
    
    var elem = document.querySelectorAll('.send\\:after');
    
    for(var i = 0; i < elem.length; i++) {
        elem[i].addEventListener("click", function(){ 
            document.querySelector(".popup").style.display = "block";
        }, false);
    }
    
    document.querySelector("#close").addEventListener("click", function(){
        document.querySelector(".popup").style.display = "none";
    });
</script>
The above code uses querySelectorAll to select all elements with the class="send:after", and then adds a click event listener to each of them. Upon clicking, the pop-up message with the class="popup" will be displayed using the style attribute display:block. The querySelector is also used to select the element with id="close" to close the pop-up message when clicked.

I hope this helps! Let me know if you have any further questions.

Answers(1)
avatar
Tolerim
a day ago
Verified Answer
To trigger the pop up message whenever people click on a button with class "send:after", you can use the following code:
<script type="text/javascript">

var button = document.querySelector(".send\\:after"); // Use double backslash to escape colon in class name

button.addEventListener("click", function(){
    document.querySelector(".popup").style.display = "block";
});

document.querySelector("#close").addEventListener("click", function(){
    document.querySelector(".popup").style.display = "none";
});

</script>
In your original code, you added a click event listener to the window object, which means the popup would appear whenever any part of the page was clicked. Instead, you should target the specific button element using document.querySelector and add the click event listener to that. Also, to select an element with a colon in its class name using document.querySelector, you need to escape the colon with a double backslash (\\:). I hope this helps! Let me know if you have any questions.
;