toggle show/hide div with button?
Hopefully this is an easy question. I have a div
that I want to toggle hidden/shown with a button
<div id="newpost">
Pure JavaScript:
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
SEE DEMO
jQuery:
$("#button").click(function() {
// assumes element with id='button'
$("#newpost").toggle();
});
SEE DEMO
Look at jQuery Toggle
HTML:
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
jQuery:
jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#content').toggle('show');
});
});
For versions of jQuery 1.7 and newer use
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#content').toggle('show');
});
});
For reference, kindly check this demo