I have just started learning about JavaScript and events. I am interested in learning the JavaScript and not jQuery until I am better at JavaScript.
I wrote this code that will show and hide my div because I basically want to be able to use this code in future web development projects but at the moment it will only apply to one element on page but what if I want to have a few pop up boxes. I understand I will have to have the element positioned absolute.
Can I also ask anyone that is good at JavaScript events to check my code to see if it is well written or if it could be improved? I am just a learning.
To make my questions clearer:
- How would I make this code more usable for more than one element?
- Is my code well written or does it look like a noob wrote it?
<style>
a#button{
background-color: #FFFF00;
display:block;
}
div#menu{
background-color: #000000;
color: #ffffff;
display:none;
}
</style>
<body>
<a id="button" href="#">Click Me</a>
<div id="menu">SUPRISE</div>
<script>
document.addEventListener("click", whereWasClicked, false); // listener for any clicks on the document.
var button = document.getElementById("button");
button.addEventListener("click", displaySuprise, false);
var clicked;
function whereWasClicked(){
clicked = event.target;
//check to see if user clicks outside of the
if (tog = 1 && clicked != menu) {
menu.style.display = "none";
document.getElementById("button").innerHTML = "Click Me";
tog = 0;
}
}
var menu = document.getElementById("menu");
var tog = 0; // set up a toggle so you can display block and then none.
function displaySuprise(){
event.preventDefault();
event.stopPropagation();
if(tog == 0){
menu.style.display = "block";
this.innerHTML = "Opened!";
tog = 1;
} else {
menu.style.display = "none";
this.innerHTML = "Click Me";
tog = 0;
}
// check to see if the user has clicked anywhere off the new element.
}
</script>
prototype
to improve modularity of the code. \$\endgroup\$