pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button.

I tried moving the #close div outside of the #bar div to see if that would solve the issue, but unfortunately it did not work.

var closeBar = document.getElementById("close");
var bar = document.getElementById("bar");
if (closeBar) {
  addEventListener('click', function() {
    bar.classList.add('superHidden');
  })
}
#bar {
  position: fixed;
  width: 100vw;
  display: flex;
  height: 50px;
  bottom: 0px;
  left: 0px;
}

ul {
  display: flex;
  justify-content: center;
  height: 100%;
  list-style: none;
}

li {
  margin: auto 0;
  font-size: 22px;
}

#close {
  position: fixed;
  right: 20px;
  bottom: 0;
  z-index: 1000;
  height: 50px;
  width: 25px;
  cursor: pointer;
}

.superHidden {
  display: none!important;
}
<div id="bar">
  <ul>
    <li><a target="_blank" href="google.com"><button >Google</button></a></li>
  </ul>
  <div id="close">
    <ul>
      <li>X</li>
    </ul>
  </div>
</div>

Answer №1

Make sure to specify a target for the event listener, or else you'll be adding a click event to the entire window:

addEventListener('click', function() {
    bar.classList.add('superHidden');
})

If you want the event to only trigger when clicking on the "close button", try this:

closeBar.addEventListener('click', function() {
    bar.classList.add('superHidden');
})

Here's the complete example:

var closeBar = document.getElementById("close");
var bar = document.getElementById("bar");
if (closeBar) {
  closeBar.addEventListener('click', function() {
    bar.classList.add('superHidden');
  })
}
#bar {
  position: fixed;
  width: 100vw;
  display: flex;
  height: 50px;
  bottom: 0px;
  left: 0px;
}

ul {
  display: flex;
  justify-content: center;
  height: 100%;
  list-style: none;
}

li {
  margin: auto 0;
  font-size: 22px;
}

#close {
  position: fixed;
  right: 20px;
  bottom: 0;
  z-index: 1000;
  height: 50px;
  width: 25px;
  cursor: pointer;
}

.superHidden {
  display: none!important;
}
<div id="bar">
  <ul>
    <li><a target="_blank" href="google.com"><button >Google</button></a></li>
  </ul>
  <div id="close">
    <ul>
      <li>X</li>
    </ul>
  </div>
</div>

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

JavaScript - What is the best way to add the same object value into an array?

After spending a few hours trying to figure out how to manage JSON data structured like this: [ { "value": "Osteonecrosis", "Diagnosis_Code": "DIAG002", "NamaCategory": "Primary Category", "FK_Diagnosis_Content_ID": 2 }, { "value ...

Unable to process login information with form method post on basic login page

Hi, I've been struggling with a simple login page issue. It works fine with Bootstrap, but I want to switch to Angular Material Design. I've been searching for the problem for about 3-4 hours and can't find anything. I suspect that the form ...

Managing asynchronous tasks that do not save their outcomes within the application state

Upon discovering a requirement within a vanilla JS webapp that necessitates a single JSON "definitions" object for rendering, I realized that the definitions are to be loaded through an HTTP request at the start, then read, parsed, and passed down to anoth ...

Problem with RadioButton click event not triggering

Among my collection of RadioButton elements, there is an onclick event that should trigger. This event, named SecurityCheckedChanged, will display or hide other div containers (populated with RadioButton elements) based on the selected RadioButton. Howeve ...

Transforming an image into a CSS-powered website menu button: Step-by-step guide

I am currently using images as button backgrounds, and I have programmed them to change when the button is clicked to give the impression that it is being pressed. However, I am looking to enhance the responsiveness of the page, so that the images also cha ...

Encountering a problem with populating data in postgresql

After executing the npm run seed command to populate data into PostgreSQL, even though the seeding process seemed to be successful, I couldn't locate the seeded data in the PostgreSQL database. Can anyone advise on what might have gone wrong or sugges ...

How can you restrict a textbox input to accept only numerical values and decimals using ng-pattern?

I'm working on a code that needs to accept both decimals and integers. How can I verify this using the ng-pattern? An example of the code: Some test cases include: 1) 22 = Should pass, 2) 22.5 = Should pass, 3) 2a = Should fail, 4) @#@ = Should ...

Issue with Electron Remote process failing to take user-defined width and height inputs

I'm currently facing an issue with utilizing remote windows in electron. I am attempting to process user input and use that input to generate a new window with specific width and height. However, when I hit submit, nothing happens. I can't figur ...

"Get rid of the arrow in Bootstrap's dropdown menu

I'm currently using a bootstrap template that features an accordion menu. However, I have come across a scenario on one section of the page where I do not require the items to expand and show additional text, therefore, I would like to remove the arro ...

Ways to incorporate color gradients into the corners of CSS cards

Below is an example of a basic bootstrap card: Example 1: https://i.stack.imgur.com/DK2Sz.png I attempted to draw blue and green colors side by side, but was only successful in drawing blue as shown below: Example 2: https://i.stack.imgur.com/CcSzP.png ...

How to temporarily toggle an event on and off using jQuery

Is there a way to control the activation and deactivation of a jQuery event? I currently have this functioning code that runs when the page is ready: $(".panzoom").panzoom({ $zoomIn: $(".zoom-in"), $zoomOut: $(".zoom-out"), $zoomRange: $(".zoo ...

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

Properties of untyped objects in TypeScript are not defined

Here is the code snippet I've been working on: file.js const channel = {}, arr = [string,string,string]; for(let i = 0;i < arr.length;i++ ){ channel[arr[i]] = "Amo" //equal string value } I have an array that contains only string values, for ...

Having trouble retrieving the component state within AgGrid's cellRenderer

When working on my React app using functional components, I encountered an issue with accessing a local state (myObj) within a cellRenderer in AgGrid. The local state is populated via a context object from the parent component based on an API response. Un ...

Verify if the username or phone number is already in use (front end)

Is there a way to verify user or phone existence on the front-end form? I'm using Yup + Formik for all my requirements, and in my backend with Sequelize, I can check if a username or phone number already exists. passport.use( 'register&apos ...

Elevate state in React to modify classNames of child elements

I have a structured set of data divided into 6 columns representing each level of the hierarchy. When a user makes selections, their chosen location is highlighted with a dynamic CSS class name and displays the relevant data list. I've managed to impl ...

Encountering a 404 Error When Making an Ajax Request in Spring MVC

Looking to implement a basic login form using Spring MVC and an APIResponseModel class with Status, Message, HTTPStatus variables. After submitting the credentials, receiving a 404 ajax response, although the Controller returns {"status":"20 ...

Tips on setting up a dropzone upload feature with a click-trigger option

Is there a way to configure dropzone.js so that the file is uploaded only when a submit button is clicked, rather than automatically? Here's the code snippet I am currently using: $('#myDropzone').dropzone({ url: SITE_URL + 'self_r ...

Leverage the power of PHP files within your JavaScript code

I have a PHP file with some calculations that I want to integrate into another JavaScript file. How can I pass variables from JavaScript to perform calculations inside the PHP file? Here is my JavaScript code: $("#upload").on("click", function(){ var ...

Is it possible to apply a background image on top of an existing image?

Is it possible to set a background image on an img tag? This is my current HTML markup: <div id="content"> <img src="my-image.jpg" alt="image" class="img-shadow"> </div> Here is my CSS code: #content img { floa ...