Is there a way for me to determine if something is hidden?

My goal is to have selector B toggle when selector A is clicked or when clicking outside of selector B. This part is working fine.

However, I'm struggling with preventing selector B from toggling back unless selector A is specifically clicked - not when clicking outside of either selectors A or B.

$(document).ready(function() {
  var Container = $(".redBar"); // Container (selector A)

  function Toggle() {
    Container.toggleClass("hide"); // Toggle Container with display none selector [to hide selector B]
  }

  // If selector B is visible
  if ($(Container).is(":visible")) {
    // On click of the document and selector A
    $(document, ".toggleBar").on("click", function(event) {
      // If the target of the click isn't selector A nor a descendant of selector A
      if (!Container.is(event.target) && Container.has(event.target).length === 0) {
        Toggle();
      }
    });
  }
});
/* Selector A */
.toggleBar {
  width: 150px;
  color: blue;
  text-transform: uppercase;
  font-weight: bold;
}

.toggleBar:hover {
  text-decoration: underline;
  cursor: pointer;
}


/* Selector B */
.redBar {
  width: 300px;
  height: 50px;
  color: white;
  text-transform: uppercase;
  font-weight: bold;
  background-color: red;
}

.hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="redBarContainer">
  <!-- selector A -->
  <div class="toggleBar">toggle bar</div>

  <!-- selector B -->
  <div class="redBar"></div>
</div>

CodePen: https://codepen.io/brilliantmojo/pen/GRoyrKg

Answer №1

After reviewing your task description, a more straightforward approach would be to link the toggle() function to the click event of the .toggleBar element and then simply perform a hide() action when a click is detected outside of the elements. This can be achieved with the following code:

jQuery($ => {
  let $redBar = $('.redBar');

  $('.toggleBar').on('click', e => {
    e.stopPropagation();
    $redBar.toggle();
  });
  
  $(document).on('click', (e) => {
    if ($redBar[0] !== e.target)
      $redBar.hide();
  });
});
/* Selector A */
.toggleBar {
  width: 150px;
  color: blue;
  text-transform: uppercase;
  font-weight: bold;
}

.toggleBar:hover {
  text-decoration: underline;
  cursor: pointer;
}


/* Selector B */
.redBar {
  width: 300px;
  height: 50px;
  color: white;
  text-transform: uppercase;
  font-weight: bold;
  background-color: red;
}

.hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="redBarContainer">
  <!-- selector A -->
  <div class="toggleBar">toggle bar</div>

  <!-- selector B -->
  <div class="redBar"></div>
</div>

Answer №2

To enable a click event on the entire document except for the element with the class .toggleBar, you can achieve this functionality by separating the actions for each element.

$(document).click(function(event) {
    if (event.target !== $('.redBar')[0]) {
      $('.redBar').addClass('hide');
    }
});
$(".toggleBar").click(function(event){
    event.stopPropagation();
    $('.redBar').toggleClass('hide');
});
/* Selector A */
.toggleBar {
  width: 150px;
  color: blue;
  text-transform: uppercase;
  font-weight: bold;
}

.toggleBar:hover {
  text-decoration: underline;
  cursor: pointer;
}


/* Selector B */
.redBar {
  width: 300px;
  height: 50px;
  color: white;
  text-transform: uppercase;
  font-weight: bold;
  background-color: red;
}

.hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="redBarContainer">
  <!-- selector A -->
  <div class="toggleBar">toggle bar</div>

  <!-- selector B -->
  <div class="redBar"></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

Experiencing difficulties with positioning text beside an image

Hello everyone, I'm a first-time poster seeking some assistance. I'm currently tackling an assessment and am struggling with the final part. The task involves creating a picture card with an image at the top, a circular image to the side, and tex ...

When attempting to send a POST request to /api/users/login, the system returned an error stating that "

Is there a way to make a post request to the mLab Database in order to determine if a user account already exists? The server's response states that the User is not defined. Can you please review my code? // @route post api/user/login# router.post(& ...

a guide on expanding a submenu in a shiny dashboard sidebar without using automated functions

I am facing a challenge in manually expanding a submenu within a sidebar on shiny dashboard. The function updateTabItems does not seem to work with nested menus, only with normal menus. For example, when I click on 'Switch tab', it switches the ...

Addressing the Compatibility Issue between jQuery Ajax Load and Firefox

To understand the issue I'm facing, please follow these steps in the latest versions of Chrome, Opera, Safari, and Explorer using this link: Click on "Blog" to Ajax load a list of links in the adjacent column. Click on "Lorem Ipsum" to Ajax load an ...

Initiating the ngOnInit lifecycle hook in child components within Angular

I am facing an issue with controlling the behavior of child components in my Angular application. The problem arises when switching between different labels, causing the ngOnInit lifecycle hook of the children components not to trigger. The main component ...

Obtaining the NodeValue from an input of type <td>

I have a HTML code snippet that I am trying to parse in order to extract the nodeValue of all elements within the table columns. <table id="custinfo"> <tr> <td><label>First Name</label></td> <td& ...

Clickable functionality disabled for form elements

I am encountering an issue with my system development task. The form elements appear to be unclickable, preventing any data entry in the fields. I have attempted moving the form tag above the first div in the code structure below as a troubleshooting step, ...

Issue with XHR loading an XML file from a local directory

Attempting to upload an XML file into an HTML document has been a challenge. I found a tutorial here This is the script that I am using: $(document).ready(function () { $.ajax({ type: "GET", url: "Lemon_Bars.xml", dataType: "xml", succe ...

Develop a built-in Button for Liking posts

Currently, I am encountering an issue with the JavaScript SDK where I am unable to create a built-in Like button. After researching, I came across this helpful resource: https://developers.facebook.com/docs/opengraph/actions/builtin/likes/ The solution pr ...

React.js Filter Component

I'm currently trying to create a filter for my "localtypes", but I'm encountering an issue where the console in my browser is displaying an empty array. My goal is to access the localtypes properties of the API that I am working with. I attempte ...

The element is being offset by SVG animation that incorporates transform properties

I'm working on creating a halo effect by rotating an SVG circular element using the transform rotate function. I've been using getBox to find the center point of the element, but when the rotation occurs, the overall image is getting misaligned w ...

Discover and select all elements that match an unidentified element using jQuery

Feeling a bit tangled up here, trying to unravel this puzzle. I'm looking to identify the first child of a container, and then retrieve its element or class to locate any similar top-level elements in that same container. For instance: <div clas ...

The JavaScript file fails to load when accessing port 8080

As I embark on my journey into backend development, please bear with me. Currently, I am working on a JavaScript program that retrieves text data from my localhost. I have set up an HTTP server using Node.js which serves as a regular HTTP server. The serve ...

Customize the CSS for the column containers in Material-UI's DataGrid with the

I am facing a challenge in trying to override the CSS property position on the .MuiDataGrid-columnsContainer. Upon reviewing the information available on https://material-ui.com/api/data-grid/#css, it seems that there is a rule defined for root but not spe ...

What is the best way to incorporate jQuery's default handsontable into an AngularJS directive?

I currently have a handsontable functioning in a non-AngularJS application, and I am in the process of developing a new version of the software that heavily utilizes AngularJS (SPA). My question is: is it possible to encapsulate the existing handsontable ...

Embedded iframe links failing to open within the designated frame

I have encountered an issue on my website where the links under the portfolio section now open in a new window instead of the intended iframe. This change occurred suddenly without any alterations to the code. Despite closely examining and trying various ...

"Everything is running smoothly on one REST endpoint, but the other one is throwing a CORS error

I am currently working on a project that involves a React client app and a Django server app. The React app is running on port 9997 and the server API is on port 9763. While the frontend is able to access some APIs successfully, there are some APIs that ar ...

Encountering an error: "Unhandled promise rejection SyntaxError: Unexpected character in JSON data at line 1 column 1."

When the submit button is clicked, my registration form data is sent using an event function called postData() in React. The user data is sent at the register route, and I have mentioned line numbers in the comments: const postData = async(event) =>{ ...

The website is failing to adapt properly to smaller screen sizes

I would share some code here, but it might be easier for you to just check out the URL instead. The issue is that the website was responsive across different screen sizes at first, but after making some changes in the CSS and HTML, it's not working pr ...

Effortlessly create a seamless transition in background color opacity once the base image has finished

I've set up a div with a sleek black background. Upon page load, I trigger an API request for an image, which is then displayed in a secondary div positioned behind the main one. After this, I aim to smoothly transition the overlaying div's opaci ...