Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript show element on click

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.

like image 746
Cyber Junkie Avatar asked Oct 15 '25 12:10

Cyber Junkie


2 Answers

document.getElementById('showDiv').onclick=function(){
  // Remove any element-specific value, falling back to stylesheets
  document.getElementById('element').style.display='';
};
like image 161
Phrogz Avatar answered Oct 18 '25 00:10

Phrogz


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 = '';
like image 43
PleaseStand Avatar answered Oct 18 '25 00:10

PleaseStand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!