One 4046
One 4046

Reputation: 53

Why my JS popup doesn't work on multiple element?

I'm actually creating a forum from scratch. This script create a popup when we click on remove, i make 2 button remove but only one work. Code:

Html Code ->

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <link rel="stylesheet" type="text/css" href="styletest.css">
  </head>
  <body>
    <a href="#" id="remove_openpopup">remove</a>
    <a href="#" id="remove_openpopup">remove2</a>

    <div id="popup" class="popup">
      <div class="popup_content">
        <span class="close">&times;</span>
        <p>Are you sure you wan't delete this categorie ?</p>
        <button class="button_popup close_button">No</button>
        <button class="button_popup close_button" onclick='document.getElementById("remove").submit()'>Yes</button>
      </div>
    </div>
  </body>
</html>

JS:

var modal = document.getElementById("popup");

var btn = document.getElementById("remove_openpopup");

var span = document.getElementsByClassName("close")[0];
var span2 = document.getElementsByClassName("close_button")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

span2.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

How can i make: when i click on remove it open my popup but remove2 open it too ? Can you help me please ? :)

Upvotes: 0

Views: 121

Answers (1)

shinyatk
shinyatk

Reputation: 1065

Just for a sample :) In HTML, I changed id="remove_openpopup" to class="remove_openpopup"

<a href="#" class="remove_openpopup">remove</a>
<a href="#" class="remove_openpopup">remove2</a>

In <script>, I would do as below.

<script>
var modal = document.getElementById("popup");
var btns = Array.prototype.slice.call(document.querySelectorAll(".remove_openpopup"));
var span = document.getElementsByClassName("close")[0];
var span2 = document.getElementsByClassName("close_button")[0];
btns.forEach(function(btn) {
  btn.onclick = function() {
    modal.style.display = "block";
  }
});
span.onclick = function() {
  modal.style.display = "none";
}
span2.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>

Upvotes: 1

Related Questions