"Exploring the dynamic manipulation of CSS display property through the use of an active class

When attempting to implement a small pop-up window for user confirmation before navigating away from the page, I encountered an issue. Upon clicking the RUN button with the id "openBtn," the pop-up window briefly appears and then disappears. I'm unsure of what went wrong.

CSS

.pop-up{
    display: none;
}

.pop-up.active{
    display: flex;
    position: absolute;
    background-color: #fff;
    font-size: 30px;
    color: #222831;
    flex-direction: column;
    align-items: center;
    height: 150px;
    width: 250px;
    top: 200px;
    left: 170px;
    border: 5px double #393E46;
    border-radius: 10px;
    box-shadow: 2px 4px 15px rgba(0, 0, 0, 0.3);
}

SCRIPT.JS

const openBtn = document.getElementById("openBtn");
const popUp = document.querySelector('.pop-up');
const stayBtn = document.getElementById("stayBtn");

openBtn.addEventListener('click', () =>{
    popUp.classList.add('active')
})

stayBtn.addEventListener('click', () =>{
    popUp.classList.remove('active')
})

HTML

<div class="controls">
    <div class="left"></div>
    <form action="" method="post" class="right">
        <input type="submit" name="fight" value="FIGHT">
        <input type="submit" name="pkmn" value="PKMN">
        <input type="submit" name="item" value="ITEM">
        <input type="submit" id="openBtn" value="RUN">
        
    </form>
</div>
<div class="pop-up">
    <p>Escape battle?</p>
    <form action="" method="post" class="buttons">
        <input type="submit" class="button" id="stayBtn" name="stay" value="Stay">
        <input type="submit" class="button" name="escape" id="run" value="Run">
    </form>
</div>

I simply wanted to provide a confirmation option for users before exiting, switching between CSS display properties of none and flex.

Answer №1

You need to add e.preventDefault() to your openBtn,

In the modal, I recommend using button type="button" instead of input="submit" for better practice. This eliminates the need for e.preventDefault()

Please note: I have kept your input controls as is, as I am not sure how you are using them.

const openBtn = document.getElementById("openBtn");
const popUp = document.querySelector('.pop-up');
const stayBtn = document.getElementById("stayBtn");

openBtn.addEventListener('click', e => {
  e.preventDefault()
  popUp.classList.add('active')
})

stayBtn.addEventListener('click', () => {
  popUp.classList.remove('active')
})
.pop-up {
  display: none;
}

.pop-up.active {
  display: flex;
  position: absolute;
  background-color: #fff;
  font-size: 30px;
  color: #222831;
  flex-direction: column;
  align-items: center;
  height: 150px;
  width: 250px;
  top: 200px;
  left: 170px;
  border: 5px double #393E46;
  border-radius: 10px;
  box-shadow: 2px 4px 15px rgba(0, 0, 0, 0.3);
}
<div class="controls">
  <div class="left"></div>
  <form action="" method="post" class="right">
    <input type="submit" name="fight" value="FIGHT">
    <input type="submit" name="pkmn" value="PKMN">
    <input type="submit" name="item" value="ITEM">
    <input type="submit" id="openBtn" value="RUN">
  </form>
</div>
<div class="pop-up">
  <p>Escape battle?</p>
  <button type="button" class="button" id="stayBtn" name="stay">Stay</button>
  <button type="button" class="button" name="escape" id="run" value="Run">Run</button>
</div>

Answer №2

When interacting with a form, each time you click a button or a submit input, a post request will be sent to the server with the provided values. By default, the browser will display the response from the server. To prevent the browser from redirecting, you must include e.preventDefault() in your code. In this specific case, you need to modify it to:

openBtn.addEventListener('click', e => {
  e.preventDefault()
  popUp.classList.add('active')
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing a promise and using async/await functions

Having an issue with my node and express function router.post('/', async (req, res) => { const playlist = new Playlist({ song: req.body.song, artist: req.body.artist }) try { const newPlaylist = await play ...

Responsive Video Embed Using Bootstrap-5

I'm facing some challenges with Bootstrap responsive video embedding. It seems like the parent container is not responding to changes, only the content within the <iframe> tag is being responsive. Any idea what might be going wrong? .embed- ...

"Organizing an object array based on a specified order array - a step-by-step

My task involves rearranging objects within an array. Let's assume this is the data array provided: const data = [ { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' }, { id: 'McfTB40vO', name: 'item ...

Tips for staying on the same tab after submitting the form

I have encountered an issue where I need to keep the current tab selected even after submitting a form or refreshing the page. This is how my View File appears: <ul class='tabs'> <li><a href='#tab1'>Tab 1< ...

Upload files either one at a time or in bulk

Encountering an issue with file upload functionality. When uploading multiple files at once, there are no problems. However, when uploading single files one at a time, each new upload overrides the previous one. Looking for a solution to this problem. Be ...

Begin the div at a width of 0 pixels and expand it towards the right

My current project involves opening a row of blocks with an animation. The desired outcome is to transition from 2 blocks to 3 blocks by clicking a button. Specifically, the block that needs to be added should appear in the middle and fade in from left to ...

Ways to automatically update React.js state when localStorage changes occur

Is it possible to automatically update the data on the cart page whenever there are changes made to the myCart array in localStorage? Below is the code that I am currently using: const [cart, setCart] = React.useState([]) React.useEffect(() => { se ...

Effortlessly sleek horizontal navigation bar designed with Liquid CSS

I've been exploring online tutorials to create a responsive horizontal drop-down menu navigation bar using just CSS and HTML. The tutorial process has been smooth so far, but I'm aiming to make my navigation bar fluid so that it adjusts seamlessl ...

In what way can you reach an unfamiliar form within a controller?

I am working with multiple dynamically generated forms, each associated with a different model. In my controller, I need to iterate through all the errors within the forms. I assign form names based on the models. <form name="{{myForm}}" novalidate> ...

Save the raw InputMask data in Formik with Material-UI

I currently have Input Mask implemented with a customized Material UI text field inside a Formik form: <InputMask mask="999-99-9999" maskChar="X" value={values.ssn} ...

Preserving scroll position when updating a partial page template using Rails and AJAX

When I am utilizing long polling, I encounter an issue where every time I use AJAX to refresh a page partial inside a scrollable div, the contents automatically scroll to the top. Is there any way to load the partial while maintaining the current scroll ...

Using ReactJS to toggle a div upon clicking

I am facing an issue with toggling a div by clicking on text within a toggle bar. I am in the process of recreating a WordPress website template in React JS that was originally built using bootstrap. You can view the original template here. So far, I have ...

Tips for utilizing the @Input directive within the <router-outlet></router-outlet> component

I am new to Angular 4 and recently discovered that in Angular, data can be passed from a parent component to a child component using @Input like this: <child [dataToPass]="test"></child> My question is, how can I achieve the same functionalit ...

'OR' separated by the <hr> tag

This particular code functions correctly on the Firefox and Chrome browsers. However, there seems to be an issue with IE and Opera, where the 'OR' text is only visible within a 2px height area. hr { height: 2px; border: 0; background-color ...

Encountering an error when integrating my library with MUI

Currently, I am working on developing a library that wraps MUI. One of the components I created is a Button, and here is the code snippet for it: import React, { ReactNode } from 'react' import Button from '@mui/material/Button'; impor ...

Utilize JavaScript to append elements to an array in each loop iteration, gradually building a single, unified

I find myself in a situation where an async request is sending data to a child react component. Upon logging the "data" in the component, I receive multiple arrays sequentially. Ideally, I would prefer not to rewrite the request in the parent component and ...

Transferring information to React (Native) hooks in a way similar to how it is done

Transitioning to Hooks in React Native has been a new learning curve for me, especially when it comes to passing data to child elements. In the past with class-based components, passing props was as simple as using XML-style syntax. A Simple Example using ...

Execute the script when the document is fully loaded

Is there a way to show a dialog in jQuery when the document loads without using <body onload="showdialog();">? Can the javascript code be placed in the main div or footer div to work like the onload event? <body onload="$('#dialog').sli ...

Pass a selected object to a dropdown/select change event using AngularJS

Plunkr : http://plnkr.co/edit/BRQ3I4hFTlgKq4Shz19v?p=preview I'm attempting to pass the selected item from a dropdown to a function within my controller. Unfortunately, I keep receiving it as undefined. HTML : <!DOCTYPE html> <html> ...

How to align the last item in the bottom row using Flexbox styling

Is it possible to center the last element when resizing the window to a smaller resolution, even though the parent's justify-content parameter is set to space-between? I understand that using center or space-around would achieve the desired result, bu ...