Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle - Hide and show

I copied w3schools hide and show toggle, but I want it to be reversed, so that the extra information isn't there from the beginning, but the button shows it.

This is the code:

html:

<button onclick="myFunction()">Click Me</button>

<div id="myDIV">
     This is my DIV element.
</div>

js:

function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
    x.style.display = 'block';
} else {
    x.style.display = 'none';
   }
}

Any help would be much appreciated!

like image 533
easyquestions Avatar asked Dec 07 '25 08:12

easyquestions


2 Answers

Solution is simple: Just hide the div.

<div id="myDIV" style="display:none"> 
    This is my DIV element. 
</div>

Even cooler if you hide it in css instead:

<div id="myDIV"> 
    This is my DIV element.
</div>

And this in your css:

#myDIV {
    display: none;
}
like image 180
techfly Avatar answered Dec 08 '25 20:12

techfly


I'd us a utility CSS class for this:

.is--hidden {
    display: none;
} 

Then you can apply it to the element by default:

<button class="mybutton">Click Me</button>
<div class="example is--hidden">Some Text</div>

and toggle it via jQuery:

$('.mybutton').on('click', function () {
    $('.example').toggleClass('is--hidden');
})

Fiddle: https://jsfiddle.net/tL5mj54n/

like image 24
mark_c Avatar answered Dec 08 '25 21:12

mark_c



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!