0

I need to click twice on the div (class="funfact") in order to active onclick event ff0(). Yes, I included the JS script in the HTML file.

var ffans = document.querySelector(".funfactans");

//ffans = fun fact answer
function ff0() {
  if (ffans[0].style.height == '0px') {
    ffans[0].style.height = '45px'
    ffans[0].style.marginBottom = '10px'
    ffans[0].style.paddingRight = '10px'
    ffans[0].style.visibility = 'visible'
    ffans[0].style.opacity = '1'
    ffans[0].style.pointerEvents = 'auto'
  }
<div class="facts">
  <div class="funfact" onclick="ff0()">Fact1</div>
  <div class="funfactans">Fact1 answer</div>
</div>
<script src="mainNew.js"></script>

5
  • 1
    Your JS is not complete. Please update the snippet I made you Commented Jun 23, 2020 at 8:03
  • Also please just do a document.querySelector(".funfactans").classList.add("otherclass") and put all the styles in your stylesheet Commented Jun 23, 2020 at 8:04
  • Lastly height="0px" vs visibility and another height is the difference between display:none and display:block Commented Jun 23, 2020 at 8:06
  • Is not document.querySelector(".funfactans") enough? Commented Jun 23, 2020 at 8:06
  • Can you please write me an answer as an answer and not as a comment? It's hard for me to understand that... Commented Jun 23, 2020 at 8:08

1 Answer 1

1
  • height="0px" vs visibility and another height is the difference between display:none and display:block

  • .style.height == '0px' cannot be tested like that

I believe you want this

window.addEventListener("load", function() {
  document.querySelector(".facts").addEventListener("click", function(e) {
    const tgt = e.target;
    if (tgt.classList.contains("funfact")) {
      tgt.nextElementSibling.classList.toggle("hide");
    }
  })
})
.funfactans {
  height: 45px;
  marginBottom: 10px;
  paddingRight: 10px;
  pointerEvents: auto;
}

.hide {
  display: none
}
<title>FunFacts</title>

<div class="facts">
  <div class="funfact">Fact1</div>
  <div class="funfactans hide">Fact1 answer</div>
  <div class="funfact">Fact2</div>
  <div class="funfactans hide">Fact2 answer</div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.