Can not set property 'onclick' of undefined [duplicated]

0

I have this code and I get this error Uncaught TypeError: Cannot set property 'onclick' of undefined

when I click on opening the modal I get the error, but I give it another click and it will be done with the error, but the idea is that there will be the modal with the first click

<button type="button" id="myBtn3" onclick="modal3()" class="btn btn-default">SOLICITAR DIAGNÓSTICO GRATUITO AHORA</button>

function modal3(){

            var modal3 = document.getElementById('myModal-3');

            var btn3 = document.getElementById("myBtn3");

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

            btn3.onclick = function() {
                modal3.style.display = "block";
            }

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

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

        }

I appreciate your help

    
asked by Daniel Salinas 07.11.2018 в 19:09
source

2 answers

0

Remove the "onclick" event from the button, which looks like this:

<button type="button" id="myBtn3" class="btn btn-default">SOLICITAR DIAGNÓSTICO GRATUITO AHORA</button>

Remove the script function and modify all the onclick events in the addEventListener:

  var modal3 = document.getElementById("myModal-3");

  var btn3 = document.getElementById("myBtn3");

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

  btn3.addEventListener("click", function(event) {
     modal3.style.display = "block";
  });


  span.addEventListener("click", function(event) {
     modal3.style.display = "none";
  });

  window.addEventListener("click", function(event) {
             if (event.target == modal3) {
      modal3.style.display = "none";
    }
  });
    
answered by 07.11.2018 / 19:38
source
-1

You have an error: It's event.target == modal3 instead of event.target == modal

  var modal3 = document.getElementById("myModal-3");

  var btn3 = document.getElementById("myBtn3");

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

  btn3.addEventListener("click",()=>{modal3.style.display = "block";});

  span.addEventListener("click",()=>{modal3.style.display = "none";});
/*
  window.onclick = function(event) {
    if (event.target == modal3) {
      modal3.style.display = "none";
    }
  };*/
#myModal-3{display:none; border:1px solid;padding:1em;}
.close{cursor:pointer}
<button type="button" id="myBtn3" class="btn btn-default">SOLICITAR DIAGNÓSTICO GRATUITO AHORA</button>

<div id="myModal-3">algo <span class="close">x</span></div>
    
answered by 07.11.2018 в 19:21