skip to Main Content

So, I wrote a piece of functional code in html and css with no display values, but if I try to change them through javascript, it only works outside an if statement that I put it into, even if the if statement is true (tried checking it through console.log).

HTML Code-block 1:

<nav class="navbar">
    <a href="#" class="nav-logo">Skill Container</a>
    <ul class="nav-menu">
        <li class="nav-item">
          <button class="contact-btn">
            <a href="#" class="nav-link" onclick="toggleShowContact()"
                >Contact Us</a>
          </button>
        </li>
    </ul>
</nav>

HTML Code-Block 2:

<div class="contact-form" style="display: none">
    <div style="font-size: 20px">
        <button class="btn-close" onclick="closeAll()">X</button>
        <h1 style="text-align: center">Contact Us</h1>
    </div>
</div>

CSS Code-Block, only for .contact-form:

.contact-form {
  background: #fff;
  width: 500px;
  margin: 65px auto;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  flex-direction: column;
  border-radius: 4px;
  box-shadow: 0 2px 25px rgba(0, 0, 0, 0.2);
}

Javascript Code-Block:

const btnContact = document.querySelector(".contact-btn");
const contactForm = document.querySelector(".contact-form");

function closeAll() {
  loginForm.style.display = "none";
  registrationForm.style.display = "none";
  contactForm.style.display = "none";
}

closeAll();

contactForm.style.display = "none";

function toggleShowContact() {
  console.log(`${contactForm.style.display}`);
  if (contactForm.style.display === "none") {
    contactForm.style.display = "flex";
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    The original code is actually perfectly fine. I had an issue with some other html code I've written for the navigation bar, where the problem started.


  2. May be u should use: window.getComputedStyle(elem).getProperty("display") in if statement.

    And then use: elem.style.display: "flex" to replace it.

    function toggleShowContact() {
      if (window.getComputedStyle(contactForm).getProperty("display") === "none" ) {
        contactForm.style.display = "flex";
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search