Home > Enterprise >  Button showing h1, then showing another h1 if clicked again
Button showing h1, then showing another h1 if clicked again

Time:11-30

I want to build a button, when I click it for the first time it shows for example an Ad, when clicked again it doesn't show the ad but the content. Here is what I tried:

const btn = document.querySelector('.btn');
const ad = document.querySelector('.ad');
const cnt = document.querySelector('.cnt');

let ads = false;

btn.addEventListener('click', () => {
      ads = true
      ad.style.display = 'block'

      if (ads) {
        ad.style.display = 'none';
        cnt.style.display = 'block';
      })
<div>
  <button >Click Me</button>
  <h1 style="display: none" >Ad</h1>
  <h1 style="display: none" >Content</h1>
</div>

CodePudding user response:

const btn = document.querySelector('.btn');
const ad = document.querySelector('.ad');
const cnt = document.querySelector('.cnt');

let ads = false;

btn.addEventListener('click', () => {
        ad.style.display = 'block'
    
        if(ads) {
        ad.style.display = 'none';
        cnt.style.display = 'block';
        }
        ads = true // new location
})
<body>
    <div>
        <button >Click Me</button>
        <h1 style="display: none" >Ad</h1>
        <h1 style="display: none" >Content</h1>
    </div>
</body>

Since you set ads to true before checking if the variable is true, the variable is true at the first click.

set it at the bottom like this

btn.addEventListener('click', () => {
        ad.style.display = 'block'
    
        if(ads) {
        ad.style.display = 'none';
        cnt.style.display = 'block';
        }
        ads = true
})

CodePudding user response:

Replace ads = true with ads = !ads to toggle it.

Currently your ads is always true, leading to your if (ads) { ... } block being executed every time.

const btn = document.querySelector('.btn');
const ad = document.querySelector('.ad');
const cnt = document.querySelector('.cnt');

let ads = false;

btn.addEventListener('click', () => {
  ads = !ads
  ad.style.display = 'block'

  if (ads) {
    ad.style.display = 'none';
    cnt.style.display = 'block';
  }
})
<div>
  <button >Click Me</button>
  <h1 style="display: none" >Ad</h1>
  <h1 style="display: none" >Content</h1>
</div>

  • Related