Click here to Skip to main content
15,916,945 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Im struggling to open a dialog window in java script with button click, But im getting some error like unable to get property "onclick" of undefined or null reference.Can u plz help me to fix this??

What I have tried:

HTML:


<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close"</span>
    <p>Some text in the Modal..</p>
  </div>

</div>
<pre>

*****js******:
<pre>r modal = document.getElementById('myModal');

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

var span = document.getElementsByClassName("close")[0];
 
btn.onclick = function() {// here I get error 
    modal.style.display = "block";
}
span.onclick = function() {
    modal.style.display = "none";
}


window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
Posted
Updated 6-Aug-18 0:11am
v3

1 solution

"btn" will be null\undefined because it can't find an item with an id of "myBtn". Make sure the js is executing after the button has been rendered, so if this is an external script make sure the script tag is blow the button, if it is on the page directly again make sure it is below the button.
 
Share this answer
 
Comments
SureshMunna 6-Aug-18 6:18am    
thank u soo much ...its working now ..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900