Caleb
Caleb

Reputation: 489

Why does my onclick funciton only work after the first click?

I am trying to make one button hide and the button that is already hidden replace where the other button was. My issue is that although my code works the first click does not work and it changes my other functions and throws everything off.

I found the same issue on quora where the answer was to not assume that display starts as "block". After I assigned both 'first' and 'second' displays it has the same issue of only working after the first click.

My html is:

        <button onclick="switchSearch();switchType();" id="switch">Switch to zip</button>
        <button id="first">Submit</button>
        <button id="second">Submit2</button>

My css is:

#first {
    display: block;
    font-size: 48px;
    position: relative;
    left: 20%;
    top: -25px;
    text-decoration: none;
    background-color: white;
    border: 1px solid black;
    float: left;
    margin-left: 27.5%;
}

#second {
    display: none;
    font-size: 48px;
    position: relative;
    left: 20%;
    top: -25px;
    text-decoration: none;
    background-color: white;
    border: 1px solid black;
    float: left;
    margin-left: 27.5%;
}

My Javascript is:

function switchSearch() {
    let a = document.querySelector('#first');
    let b = document.querySelector('#second');
    if (b.style.display === "none") {
        b.style.display = "block";
        a.style.display = "none";
    } else {
        b.style.display = "none";
        a.style.display = "block";
    }
}

Upvotes: 1

Views: 47

Answers (3)

Dan Fletcher
Dan Fletcher

Reputation: 1228

You just have your logic backwards.

Try this:

function switchSearch() {
  let a = document.querySelector("#first");
  let b = document.querySelector("#second");
  if (a.style.display === "none") {
    b.style.display = "none";
    a.style.display = "block";
  } else {
    b.style.display = "block";
    a.style.display = "none";
  }
}

The way you set up the default display values made it so the first call to your function just set the displays to what they already were.

Upvotes: 1

Robo Robok
Robo Robok

Reputation: 22673

The reason is that your a.style.display and b.style.display return an empty string before you click anything.

Why?

element.style doesn't always return actual style property. To check the current style value for an element, there's window.getComputedStyle() method for you:

if (window.getComputedStyle(b).display === "none") {/* ... */}

I wouldn't recommend this approach though. It's cleaner to keep your data in variables instead of keeping logic in DOM.

Upvotes: 1

Aioros
Aioros

Reputation: 4383

Your elements don't have a style property, so the first time b.style.display is actually undefined. An easy fix would be:

if (b.style.display != "block") {
    b.style.display = "block";
    a.style.display = "none";
} else {
    b.style.display = "none";
    a.style.display = "block";
}

Upvotes: 1

Related Questions