keaux
keaux

Reputation: 39

Repositioning a CSS container

I have a functional Javascript popup button. When the popup button is clicked however, the position of the page goes back to the top. This also happens when I press the close button. I believe it's because the popup container is set at a specific position. How do I make it so the page stays in the same position when the button is clicked and still displays the button?

HTML:

    <div class="container">
        <h1>Lorem Ipsum</h1>
        <br>
        <div class="box button">
            <a href="#">Lorem Ipsum</a>
        </div>
        <div class="popup">
            <h2>Lorem Ipsum</h2>
            <video src="video.mov"controls></video>
            <p>
                Insert Text Here
            </p>
            <a href="#" style="border: 2px solid; padding: 5px;">CLOSE</a>
        </div>
    </div>

CSS:

.container 
{
  margin:2em 2em;
  display:grid;
  grid-template-columns: repeat(2,340px);
  grid-gap: 55px;
}
.box 
{
  border: 3px solid;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: "Glacial Indifference", sans-serif;
  font-size: 30px;
  padding: 10px;
  border-radius: 5px;
  border-color: #FFFFFF;
  height: 170px;
  position: relative;
}

.popup
{
  display: none;
  visibility: hidden;
  position: fixed;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 800px;
  height: 600px;
  padding: 50px;
  box-shadow: 0 5px 30px rgba(0,0,0,.30);
  background: #A6A6A6;
}

.active
{
 display: block;
 top: 45%;
 visibility: visible;
 left: 50%;
}

JS:

//Popup
function open() {
  document.querySelectorAll(".button a").forEach((a) => {
    a.parentElement.nextElementSibling.classList.remove("active");
  });
  this.parentElement.nextElementSibling.classList.add("active");
  //popup is sibling of a's parent element
  document.querySelector('.body').classList.add('blurred'); 
}

function close() {
  this.parentElement.classList.remove("active"); // .popup
  document.querySelector('.body').classList.remove('blurred');
}

Upvotes: 0

Views: 133

Answers (2)

prathameshk73
prathameshk73

Reputation: 1088

Use href="javascript:void(0);". It will prevent the page from scrolling.

  <div class="container">
        <h1>Lorem Ipsum</h1>
        <br>
        <div class="box button">
            <a href="javascript:void(0);">Lorem Ipsum</a>
        </div>
        <div class="popup">
            <h2>Lorem Ipsum</h2>
            <video src="video.mov"controls></video>
            <p>
                Insert Text Here
            </p>
            <a href="javascript:void(0);" style="border: 2px solid; padding: 5px;">CLOSE</a>
        </div>
    </div>

Upvotes: 1

Kevyn Klava
Kevyn Klava

Reputation: 316

Your problem is that you are using <a href="#"></a>.

This will scroll to the top of the page, try use a <button type="button"> instead

Upvotes: 0

Related Questions