Tap on an unfilled section of a full-size element to assign a class

I need to remove the .visible class when clicking in the empty space of a full-height header.

The header contains a container that does not have full height.

Clicking on the container or its links should not trigger the removal of the class, but clicking on the remaining space below the container should.

Can this be achieved with the current HTML and CSS structure?

Link to example

$('body').on('click', '.button', function(){
  $('body').toggleClass('visible');
});
$('.visible *:not(.container)').click(function() {
  alert('clicked the outside');
  $('body').removeClass('visible');
  return false;
});

Answer №1

To create a more specific event handling in your code, you can bind a click event to the <header> element and another click event to its inner <div>. By stopping the propagation of the event, only the more specific one (the div) will be executed:

$( document ).ready(function() {
    $('body').on('click', '.button', function(){
      $('body').toggleClass('visible');
    });
    $('header').click(function() {
      alert('clicked outside the container');
      $('body').removeClass('visible');
      return false; 
    });
  $('.container').click(function(e){
    alert ('clicked inside the container');
    e.stopPropagation();
  })
});
* {
  padding:0;
  margin:0;
}
body.visible header {
  display:block;
}
header {
    top: 0;
    bottom: 0;
    position: fixed;
    overflow-y: scroll;
    overflow-x: hidden;
    background-color: rgba(0,0,0,.5);
    display: none;
    z-index: 999;
    width: 100%;
    overflow: visible;    
}
.container {  
  background: #ccc;
  padding:30px;
}
ul {
  padding:0;
  margin:0;
}
a {
  display:block;
}
.button {
  position:absolute;
  top:0;
  z-index:9999;
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <body>
    <div class="button">Button</div>
    <header>
      <div class="container">
        <ul>
          <li><a href="#">asd</a></li>
          <li><a href="#">asdas</a></li>
          <li><a href="#">asdsa</a></li>
          <li><a href="#">asdasda</a></li>
        </ul>
      </div>
      
    </header>
  </body>
</html>

Answer №2

To ensure proper functionality, it is recommended to attach a click event handler to all elements and verify if the body contains a specific class:

$('body *:not(.container)').click(function() {
    if($('body').hasClass('visible')){
      alert('You clicked outside');
      $('body').removeClass('visible');
      return false;
    }
});

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

What is the best way to find the maximum and minimum values within a nested array in JavaScript?

I am looking to extract the highest and lowest values from specific data points within a nested array. For example, this nested array is structured as [latitude, longitude]. The specific nested array in question looks like this: [[40, 50], [50, 60], [60, ...

I noticed that my Angular routes are prefixed with a '#%2F' before the specified URL in my app.js file

My Angular routes are set up in the app.js file like this: .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs ...

The axios GET request suddenly transforms into an Options request, returning a 401 Unauthorized status. Miraculously, Post

I am well-versed in the concept of "preflight request" and my server does indeed support options requests. What perplexes me is that I have tested various online API tools like Postman and reqbin, which work perfectly fine. However, when I attempt to use ...

What is the method for swapping out the numerical ending of a value three times, increasing the ending, and then looping it with Text Pastry?

I am faced with the task of generating 210 unique checkboxes, each requiring its own distinct name, id, and label for value. These checkboxes are organized in tables, with each table containing 6 checkboxes. So far, I have manually configured 54 checkbox ...

Sending variable from JavaScript via AJAX to PHP results in an undefined variable

My goal is to pass the variable rating_index to my PHP code and then send it to the database. Although the actual code for rating_index is quite long, I can confirm that right before the AJAX call, I console.log(rating_index) and it displays an integer val ...

What is the best way to merge all project modules into a single file using the r.js optimizer?

While working with the r.js optimizer, I noticed that the final index.html file doesn't seem to allow for referencing just a single script without making any async calls to other scripts during a user's session. It appears to generate multiple gr ...

Using the timeago jQuery plugin to replace time_ago_in_words in an internationalized Rails 3.2 application

While running my completed Rails Tutorial application through Rails Best Practices, I received a warning advising against using the time_ago_in_words method due to it being "too expensive to calculate the time on the server side." Instead, they suggested u ...

Easy steps to assign an id to a div element generated from a multidimensional array

I am facing a challenge with a function I have created to generate a table by fetching data from a database. Due to the automatic extraction of data within this function, I am unable to apply different CSS properties such as text alignment (left, center, a ...

Can a `react` app with `mysql` be uploaded to `github`?

I recently created a basic online store with the help of react, node, and mysql. I am considering uploading it to github, but I'm uncertain if I can do so while my database is currently stored on localhost. Any advice? ...

MongoDB failing to enforce unique constraints on partial indexes

I have a set of data that looks like this: { name: "Acme co." add4: "", nationalNumber: "+13412768376" }, { name: "Acme Inc.", add4: "6345", nationalNumber: "" } My goal is to insert these records into a collection, but only if they are uni ...

Concerning the development of React components

Currently, I am diving into the world of React and ES6. Along this learning journey, I came across an interesting code snippet below. import { getBoxStyle } from './PythagorasTree.js' export const TreeBox = (props) => { const style = getBox ...

Issue with JQuery functionality not triggering in React component without requiring a page reload

My Ruby on Rails blog app with React views consists of two tables: posts and comments. Each post includes a hidden comments section that can be toggled to view by clicking a button. Here is the JQuery event responsible for enabling this functionality: $( ...

In TypeScript, at what level should the timeout be specified?

I'm currently working on writing a debounce function in TypeScript, but I'm feeling uncertain about the type that should be assigned to a variable used with setTimeout. This is the snippet of my code: function debounced(func: () => void, wait ...

An unexpected key was found in the create store function in React Redux

Encountering the issue An unexpected key "characters" was found in the initialState argument passed to createStore. Expected keys are: "marvelReducer", "routing". Any unexpected keys will be disregarded. rootReducer : import { combineReducers } from &a ...

Executing a Mysql callback inside another callback in Node.js

Hi, I've hit a roadblock with my first callback function "selectArticleByTitle(title, callback)". The terminal keeps throwing the error "Cannot read property 'id' of undefined". I'm unsure how to properly complete the first callback so ...

Customize the appearance of each TreeItem in JavaFX using CSS to assign unique

I am looking for a way to color individual Tree Items in a treeView based on specific conditions. I found a promising answer, but unfortunately, I am struggling to implement it. You can check out the answer here. My main obstacle is understanding how to u ...

Require a password in order to access a specific webpage

I recently created a basic website with one page (main.html) to showcase my Curriculum Vitae. However, in order to restrict access and only allow specific individuals to view it, I am looking for a simple way to add a password requirement (without the nee ...

Navigating the parent-child hierarchy in Three.js

Two cubes were created with specific dimensions. The first cube had a width of 2083, height of 1987, and depth of 0. The second cube had a height of 40, width of 80, and depth of 0. The second cube was then positioned inside the first cube as its child wit ...

Guidance on implementing a source map in a Node.js VM

Currently, I am analyzing JavaScript bundled source code in Node.js using the following snippet of code: const javascriptCode = "..." const javascriptSourceMap = "..." const wrapper = NativeModule.wrap(javascriptCode); const script = ne ...

Angular service unable to maintain data continuity across multiple controllers

I am facing an issue while attempting to set the title in controller1 using a service and then accessing the updated title in controller2. The function sharedProperties.setTitle(title) works perfectly fine in controller1, however, in controller2, I keep g ...