optimize javascript display style

How can I optimize that style.display JavaScript, I don't wanna use "count" variable, it's just a w3school example and I wonder how to optimize it without using "count" variable?

<!DOCTYPE html>
<html>
<body>

    <h2>What Can JavaScript Do?</h2>

    <p id="demo">JavaScript can hide HTML elements.</p>

    <button type="button" onclick=show()>Click Me!</button>

</body>

<script>
count = 0
function show() {
    if (count%2==0) {
        document.getElementById('demo').style.display='none'
    } else {
        document.getElementById('demo').style.display='block'
    }
    count++;

}
</script>
</html> 

Upvotes: 0

Views: 62

Answers (4)

Pingolin
Pingolin

Reputation: 3417

If you don't want to use extra CSS and non-intrusive Javascript:

var btn = document.getElementById('btn');
var demo = document.getElementById('demo');
demo.style.display = 'block';

btn.addEventListener('click', function() {
  demo.style.display = demo.style.display === 'block' ? 'none' : 'block';
});
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button" id="btn">Click Me!</button>

Upvotes: 0

Jai
Jai

Reputation: 91

use a boolean.

<script>
hide = false;
function show() {
    hide = !hide
        if (hide) {
            document.getElementById('demo').style.display = 'none'
        } else {
            document.getElementById('demo').style.display = 'block'
        }
}
</script>

Upvotes: 0

Sandeep Manne
Sandeep Manne

Reputation: 6092

You are basically toggling the div, so you can achieve that by writing in the following way.

function toggle() {
  if (document.getElementById('demo').style.display === 'block') {
    document.getElementById('demo').style.display='none'
  } else {
    document.getElementById('demo').style.display='block'
  }
}
<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick=toggle()>Click Me!</button>

</body>

</html> 

Upvotes: 0

brk
brk

Reputation: 50291

You can use classList.toggle

function show() {

  document.getElementById('demo').classList.toggle('hide')

}
.hide {
  display: none;
}
<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick=show()>Click Me!</button>

Upvotes: 2

Related Questions