Skip to content
Advertisement

How do I toggle CSS features with JS functions

I want to run my function which then starts displaying a CSS element, I currently have

CSS

.popUpNames{
  color:white;
  text-shadow: 1px 1px 1px white;
  padding:5px;
  border:black 5px solid;
  border-radius: 5px;
  display:block;
  position: fixed;
  top: 50%;
  left: 50%;
  background-color: #1a1a1a;
  transform: translate(-50%, -50%);
  visibility: hidden;
}

.popUpNames .show {
  visibility: visible;
}

HTML

<div class="popUpNames">
    <p></p>
  </div>

JS

function togglePopup() {
  var popup = document.getElementById("popUpNames");
  popup.classList.toggle("show");
}

(the function is called within another function, the calling of the function itself works)

I’ve tried to chnange the id’s to classes, the order of .popUpNames .show and the regular .popUpNames

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_popup I tried extrapolating it from this website, but to no avail

Advertisement

Answer

TechStudent10 is right about needing to change .popUpNames .show to .popUpNames.show. You also need to do a couple other things:

  • Change document.getElementById("popUpNames") to document.querySelector(".popUpNames")
  • Remember to call togglePopup() after the DOM has loaded (otherwise it’ll stay hidden).

document.addEventListener('DOMContentLoaded', () => {
  togglePopup();
});

function togglePopup() {
  const popup = document.querySelector(".popUpNames");
  popup.classList.toggle("show");
}
.popUpNames {
  color:white;
  text-shadow: 1px 1px 1px white;
  padding:5px;
  border:black 5px solid;
  border-radius: 5px;
  position: fixed;
  top: 50%;
  left: 50%;
  background-color: #1a1a1a;
  transform: translate(-50%, -50%);
  display: none;
}

.popUpNames.show {
  display: block;
}
<div class="popUpNames">
  <p>paragraph</p>
</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement