What is the best way to create a close button using JavaScript?

I just started learning JavaScript and I want to figure out how to make the close button close the div .popup1 in the following code:

https://jsfiddle.net/74hmx0vb/1

<div class='popup1' id="popup1">
  <div class="container">
    <div class="row rowpopup">
      <div class="iconpopup">
        <img class="imgpopup" src="" />
      </div>
      <div class="textpopup">
        <div class="textpopup1">

        </div>
        <div class="textpopup2">

        </div>
      </div>
      <button type="button" class="close" aria-label="Close">
        <span aria-hidden="true"gt;&times;</span>
      </button>
    </div>
  </div>
  </div>

My plan is to make the close button trigger a function upon clicking to add a class with display: none. Would that be the best approach? I also want to include a fadeout transition when the close button is clicked.

Can anyone provide guidance on how to achieve this? Are there any alternate solutions I should consider?

Answer №1

You can simply utilize the display:none property in JavaScript without the need to include any additional classes:

Using JavaScript:

function hidePopup() {
    document.getElementById('popup1').style.display = "none";
}
.popup1 {
  height: 100px;
  width:300px;
  position: fixed;
  z-index: 99999;
  background: white;
  bottom: 50px;
  left:50px;
  border-radius: 10px;
  box-shadow: 0 0 30px rgba(0,0,0,0.45);
    -moz-box-shadow: 0 0 30px rgba(0,0,0,0.45);
    -webkit-box-shadow: 0 0 30px rgba(0,0,0,0.45);
}

.rowpopup {
  display: inline-flex;
}

.textpopup {
  padding: 10px;
  margin-top: -15px;
}

.textpopup1 {
  font-size:16px;
}

.textpopup2 {
  font-size:14px;
}

.iconpopup {
  padding:10px;
}

.imgpopup {
  width:30px;
}

.hidepopup {
  display: none !important;
}
<div class='popup1' id="popup1">
  <div class="container">
    <div class="row rowpopup">
      <div class="iconpopup">
        <img class="imgpopup" src="https://cdn.shopify.com/s/files/1/0076/6931/7690/files/clock2.png?8339" />
      </div>
      <div class="textpopup">
        <div class="textpopup1">
          Order as soon as possible
        </div>
        <div class="textpopup2">
          There is little time remaining for this deal to end
        </div>
      </div>
      <button type="button" onclick="hidePopup()" class="close" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
  </div>
</div>

Alternatively, using inline JavaScript code:

.popup1 {
  height: 100px;
  width:300px;
  position: fixed;
  z-index: 99999;
  background: white;
  bottom: 50px;
  left:50px;
  border-radius: 10px;
  box-shadow: 0 0 30px rgba(0,0,0,0.45);
    -moz-box-shadow: 0 0 30px rgba(0,0,0,0.45);
    -webkit-box-shadow: 0 0 30px rgba(0,0,0,0.45);
}

.rowpopup {
  display: inline-flex;
}

.textpopup {
  padding: 10px;
  margin-top: -15px;
}

.textpopup1 {
  font-size:16px;
}

.textpopup2 {
  font-size:14px;
}

.iconpopup {
  padding:10px;
}

.imgpopup {
  width:30px;
}

.hidepopup {
  display: none !important;
}
<div class='popup1' id="popup1">
  <div class="container">
    <div class="row rowpopup">
      <div class="iconpopup">
        <img class="imgpopup" src="https://cdn.shopify.com/s/files/1/0076/6931/7690/files/clock2.png?8339" />
      </div>
      <div class="textpopup">
        <div class="textpopup1">
          Order as soon as possible
        </div>
        <div class="textpopup2">
          There is little time remaining for this deal to end
        </div>
      </div>
      <button type="button" onclick="document.getElementById('popup1').style.display = 'none'" class="close" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
  </div>
</div>

Answer №2

Indeed, a function that adds a class can achieve the desired effect. For example, you can create a function that adds a class when the close button is clicked like this:

var popupEl = document.querySelector('.popup1');
var button = document.querySelector('.close');

button.addEventListener('click', function() {
   popupEl.classList.add('closed');
});

This will update your DOM to resemble something like:

<div class='popup1 closed' id="popup1">
....

To hide the element using opacity with a smooth transition, you can define your CSS like so:

.popup {
   opacity: 1;
   transition: opacity 0.5s ease-out;
}

.closed {
   opacity: 0;
}

To completely hide or remove the element from the DOM, you can listen for the transitionend event to trigger removal like this:

popupEl.addEventListener('transitionend', function(){
   popupEl.classList.add('removed');
});

// css
.removed {
   display: none;
}

Keep in mind that transitionend triggers in both directions, so ensure that the removed class is only added when the closed class is present on the element, as shown below:

popupEl.addEventListener('transitionend', function(){
   if( popupEl.classList.contains('closed') ) {
      popupEl.classList.add('removed');
   }
});

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

showing errors in case the username does not match the specified pattern

As I work with symfony, one of the challenges is displaying errors when the username does not fit the specified pattern. How can this be achieved? {{ form_widget(form.username, {'attr':{'pattern': '[a-zA-Z]*'} }) }} ...

Can someone show me how to implement RequestPromise in TypeScript?

I recently integrated the request-promise library into my TypeScript project, but I am facing some challenges in utilizing it effectively. When attempting to use it in the following manner: import {RequestPromise} from 'request-promise'; Reque ...

Use the resizable function for widths greater than 1024px

I have a resizable function on my page: $(function() { $( "#droppable" ).droppable({ create: function( event, ui ) {$( this ).hide(0)} }); $( "#droppable" ).on( "dropover", function( event, ui ) { $( this ) $( this ).text('¿Eliminar?&apo ...

What is the best way to store user data from an Angular App into the Firebase Realtime database?

As I delve into the world of Angular by following a tutorial, I find myself struggling with saving users to the Firebase database. Despite successfully logging in, the database remains empty. import { Injectable } from '@angular/core&apo ...

Internet Explorer IE 11 encounters an "Error: Object does not support property or method" issue

Recently, I started using the jquery circleChart.min.js plugin for creating a circle chart. It's been working perfectly on all browsers except for Internet Explorer 11 (IE11). I keep getting an error message when trying to run it in IE11. Can anyone h ...

Check if array2 is partially ordered as array1 in JavaScript

Is there a more efficient way to achieve these conditions in JavaScript using vanilla or lodash? const array1 = [1, 2] const array2 = [1, 2, 3, 4] //true const array2 = [1, 3, 2, 4] //true const array2 = [4, 3, 2, 1] //false const array2 = [2, 3, 1, 4] / ...

Why does the Formik form only validate after the second button click in this React Hooks, TypeScript, Formik, NextJS setup?

Looking for fresh perspectives on my code. The issue lies in the fact that it takes two submission attempts to validate the data inputted into a form successfully. It appears that the post request to Airtable happens before the validation schema, resulting ...

Matching the heights of child elements in different block elements using CSS (flex/grid)

Hey there! I need some help with a markup issue. I want to replicate the layout shown in this picture. The challenge is ensuring that the grey line between the upper and lower sections of cards on the same row are aligned perfectly. In the image, you can s ...

Where should custom PHP code be placed in Prestashop 1.7.5?

Currently, I am facing the challenge of incorporating a custom PHP code snippet into Prestashop's file structure so that it is accessible on all pages such as the cart, categories, and CMS pages. After some research, I have found suggestions to place ...

Adding initial data to MongoDB in ExpressJS: What's the best way to include fixture data upon startup?

I've set up my expressjs server and mongoDB (using the mongoDB native driver and not mongoose). I want to check for existing documents in the database and add some fixture documents when the server starts, but I'm unsure where to do that. Someth ...

What is the best way to target the iframe within the wysihtml5 editor?

Currently, I am utilizing the wysiwyg editor called wysihtml5 along with the bootstrap-wysihtml5 extension. As part of my project, I am designing a character counter functionality that will showcase a red border around the editor area once a specific maxl ...

Change a TypeScript alias within the @types namespace

While using Typescript 3, I encountered a situation where I needed to modify a type alias from the @types/json-schema definition provided by DefinitelyTyped. The issue arose when I wanted to incorporate a custom schema type into my code. Since this custom ...

Display a specialized stock message in WooCommerce upon selecting a size variant

While working on my product detail page, I have implemented the following logic: https://i.sstatic.net/G98hX.png To enable this functionality, I have made modifications to the functions.php file in the active child theme: // Enqueue JavaScript for handlin ...

Encountering difficulty in adding content to a table using JavaScript. An error message appears stating that assignment to a function

I am utilizing ajax to retrieve an item from a web API, and then attempting to allocate attributes of that item to a table: function find() { var id = $('#contentID').val(); $.getJSON(uri + '/' + id) .done( ...

Starting objects before utilizing them in the useFrame() function in react-three-fiber

I am currently working on a project using react-three-fiber to create a scene. However, I am facing an issue with placing 3D objects at different random positions. I tried using a for loop inside useFrame to set random positions, but this causes the partic ...

Updating DOM element value from controller in AngularJs following an AJAX request

Currently, I am facing an issue in my code where I want to display a progress bar and hide it until isLoaded becomes true. <uib-progressbar class="progress-striped active" value="100" type="warning" ng-hide="{{isLoaded}}"></uib-progressbar> I ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

various designs for multi-location infrastructure in angular js

Our angular app is designed with a multi-site architecture, where the base URL of each domain varies. Each site requires a unique header and footer to be incorporated, along with custom CSS and links specific to that site. Is there a way to dynamically in ...

Is it a graphics card malfunction or a coding complication? Delving into THREE.JS WebGL

Recently, I created a cool scene using three.js that was running perfectly until today. Strangely, without any changes to the code, I started encountering an error in every major browser - Chrome, Firefox, and Edge. The error message I am seeing is: THREE. ...

The For loop with varying lengths that exclusively produces small numbers

I'm currently using a for loop that iterates a random number of times: for(var i = 0; i<Math.floor(Math.random()*100); i++){ var num = i } This method seems to be skewed towards producing lower numbers. After running it multiple times, the &apo ...