Home > database >  How do I toggle CSS features with JS functions
How do I toggle CSS features with JS functions

Time:11-28

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 >
    <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

CodePudding user response:

You added a space between .popUpNames and .show in your CSS file. This is going to apply this style to elements that have .popUpNames or .show. Not and. In order to fix this, remove the space between the two classes so that you have .popUpNames.show.

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

.popUpNames.show {
  display: block;
}

I also removed the visibility property because you are already using display.

Another thing (pointed out by @Mister Jojo) is that you are getting the element using the getElementById function, but you haven't even assigned an ID to your HTML element. Add an ID to your HTML element by adding id="<your id here>" to it.

CodePudding user response:

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 >
  <p>paragraph</p>
</div>

  • Related