Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading