easyquestions
easyquestions

Reputation: 135

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!

Upvotes: 3

Views: 7869

Answers (5)

Ilya Kushlianski
Ilya Kushlianski

Reputation: 968

No changes to styles or HTML required. Your javascript should be the following:

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

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

The first function runs and hides your div and the second reacts to clicks and toggles the div.

Upvotes: 2

mark_c
mark_c

Reputation: 1212

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/

Upvotes: 3

Matt
Matt

Reputation: 5428

Here's a snippet example

Set the style to hide the element (display:none) from the start. Toggle it on click.

document.getElementById('myButton').onclick = function() {
  var x = document.getElementById('myDIV');
  x.style.display = x.style.display === 'none' ? 'block' : 'none';
};
<button id='myButton' >Click Me</button>

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

Upvotes: 1

techfly
techfly

Reputation: 1866

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;
}

Upvotes: 5

The_Outsider
The_Outsider

Reputation: 1925

You just need to add display : none in your code.

function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
    x.style.display = 'block';
} else {
    x.style.display = 'none';
   }
}
<button onclick="myFunction()">Click Me</button>

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

Upvotes: 2

Related Questions