I'm trying to do this without Jquery. I want to show a div when clicking a trigger. So far I have this to hide the element.
document.getElementById('element').style.display = 'none';
HTML..
<div class="element">Ahem, boo!!</div>
<a href="#" id="showDiv">Show</a>
How do I create a function to show the div when clicking the link? I would like to avoid using functions like onclick="showDiv()
in the link itself.
I'm trying to do this without Jquery. I want to show a div when clicking a trigger. So far I have this to hide the element.
document.getElementById('element').style.display = 'none';
HTML..
<div class="element">Ahem, boo!!</div>
<a href="#" id="showDiv">Show</a>
How do I create a function to show the div when clicking the link? I would like to avoid using functions like onclick="showDiv()
in the link itself.
3 Answers
Reset to default 9document.getElementById('showDiv').onclick=function(){
// Remove any element-specific value, falling back to stylesheets
document.getElementById('element').style.display='';
};
It's possible to attach event handlers completely within JavaScript. Example:
document.getElementById('showDiv').onclick = function() {
// Do whatever now that the user has clicked the link.
};
To reverse the effect of the first line of code you posted, you could use:
document.getElementById('element').style.display = 'block'; // or
document.getElementById('element').style.display = '';
Add this to the script:
function myFunction() {
var btn = document.getElementById("myButton");
//to make it fancier
if (btn.value == "Click To Open") {
btn.value = "Click To Close";
btn.innerHTML = "Click To Close";
}
else {
btn.value = "Click To Open";
btn.innerHTML = "Click To Open";
}
//this is what you're looking for
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
and edit the button and div:
<button onclick="myFunction()" id="myButton" value="Click To Open Instructions">Click To Open Instructions</button>
<div style="display:none;" id="myDIV">
</div>
onclick
attribute in HTML, along with all other JavaScript event handlers in your HTML. – Phrogz Commented Dec 5, 2010 at 4:05blockquote
to visually indent content that is not a quote is incorrect. – Phrogz Commented Dec 5, 2010 at 4:23