Is there a way to display an element only when it is clicked on, and then hide it when other elements are clicked on?

Description: My webpage includes two buttons and two additional elements (div & section). When button 1 is clicked, the div element appears with a HotPink background-color. If button 1 is clicked again, the div element disappears. Similarly, button 2 reveals the section element with a DarkGreen background-color when clicked, and hides it upon a second click.

An added functionality allows both the div and section elements to disappear by clicking on the white space of the body.

Question: How can I create a function that shows the div element when button 1 is clicked, and then hides it when button 2 or any other element on the web page is clicked???

Demo

NOTE: Instead of duplicating code for different classes under separate events, please suggest a more efficient method.

My codes: HTML:

<button class="button1">
Show Div Element
</button>
<div class="div">
I am Div Element
</div>

<br><br>

<button class="button2">
Show Section Element
</button>
<section class="section">
I am Section Element
</section>

JQuery:

$(function(){

    $(".button1").click(function(event){
    event.stopPropagation();
    if($(".div").css("display") == "none"){
        $(".div").css("display","block");
    }else{
        $(".div").css("display","none");
    }
  });

  $(".button2").click(function(event){
    event.stopPropagation();
    if($(".section").css("display") == "none"){
        $(".section").css("display","block");
    }else{
        $(".section").css("display","none");
    }
  });

  $(document).click(function(){
    $(".div").css("display","none");
    $(".section").css("display","none");
  });

});

Answer №1

To simplify the process, you can initiate the .click functions for both button 1 & 2 by adding:

.css("display","none");

This function will hide the other element as shown below:

$(".button1").click(function(event){

    $(".section").css("display","none");

    event.stopPropagation();
    if($(".div").css("display") == "none"){
        $(".div").css("display","block");
    }else{
        $(".div").css("display","none");
    }
});

$(".button2").click(function(event){

    $(".div").css("display","none");

    event.stopPropagation();
    if($(".section").css("display") == "none"){
        $(".section").css("display","block");
    }else{
        $(".section").css("display","none");
    }
});

Answer №2

Method that does not rely on JQuery... However, feel free to use it if you so desire.

const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);

$('.button1').addEventListener('click', ()=>{
    toggle('div')
});
$('.button2').addEventListener('click', ()=>{
    toggle('section')
});

function toggle(element){
    if($('.show')){
        Array.from($$('.show')).forEach((ele) => {
            ele.classList.remove('show');
        });
    }
    $(element).classList.add('show');
}
html, body {
    background-color: #fafafa;
    width: 100%;
    height: 100%;
    padding: 12px;
    margin: 0;
}

.button1 {
    background-color: pink;
    position: relative;
    display: inline-block;
    padding: 8px;
    border: none;
    margin: 0 0 6px 0;
    cursor: pointer;
}

.div {
    background-color: hotpink;
    display: none;
    width: 160px;
    height: 160px;
}

.button2 {
    background-color: green;
    position: relative;
    display: inline-block;
    padding: 8px;
    color: white;
    border: none;
    margin: 0 0 6px 0;
    cursor: pointer;
}

.section {
    background-color: darkgreen;
    display: none;
    width: 160px;
    height: 160px;
    color: white;
}

.show {
    display: block;
}
<button class="button1">
        Show Div Element
    </button>
    <div class="div">
        I am Div Element
    </div>

    <br>
    <br>

    <button class="button2">
        Show Section Element
    </button>
    <section class="section">
        I am Section Element
    </section>

Answer №3

This method depends on event bubbling, so there is a chance it could malfunction if other handlers prevent propagation.

Additionally, please keep in mind that this implementation currently relies on the specific HTML structure provided, but it can be easily adjusted as needed.

$(document).click(function(e) {
  $elem = $(e.target)
  // Check if the element is visible to avoid reopening
  needToggle = $elem.is('button') && !$elem.next().hasClass("open")
  $(".open").removeClass("open") // Close all open elements
  if (needToggle) {
    $elem.next().toggleClass("open")
  }
})
html,
body {
  background-color: #fafafa;
  width: 100%;
  height: 100%;
  padding: 12px;
  margin: 0;
}

.button1 {
  background-color: pink;
  position: relative;
  display: inline-block;
  padding: 8px;
  border: none;
  margin: 0 0 6px 0;
  cursor: pointer;
}

.div {
  background-color: hotpink;
  display: none;
  width: 160px;
  height: 160px;
}

.button2 {
  background-color: green;
  position: relative;
  display: inline-block;
  padding: 8px;
  color: white;
  border: none;
  margin: 0 0 6px 0;
  cursor: pointer;
}

.section {
  background-color: darkgreen;
  display: none;
  width: 160px;
  height: 160px;
  color: white;
}

.open {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button1">
Show Div Element
</button>
<div class="div">
  I am Div Element
</div>

<br><br>

<button class="button2">
Show Section Element
</button>
<section class="section">
  I am Section Element
</section>

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

Building a Collapseable and Non-Collapseable Bootstrap4 NavBar in ReactJS

Is there an easy solution for creating a collapsible horizontal NavBar? <Navbar inverse fixedTop fluid collapseOnSelect> <Navbar.Header> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> ...

Using PHP to extract an image in HTML

I have a server-side PHP file that retrieves a jpeg image from the server using echo file_get_contents(). My goal is to fetch this image through Ajax and display it in an HTML file on the client side. Although I am successfully able to receive the image ...

Constantly scrolling screen in android Webview

When working with an Android web view, I encountered a bug related to infinite scrolling. Interestingly, removing the routerLink in certain pages resolved the issue, but not consistently across all cases. Is there a way to address this bug from the Android ...

Tips for embedding HTML content onto a clipboard for easy pasting into Gmail

Our application generates two URLs that users often want to copy and paste into Gmail. To make these links more visually appealing than the lengthy URLs, we implemented HTML code. We included a feature that places the HTML on the Windows clipboard for easy ...

Utilizing the functionalities of HTML5 in conjunction with XHTML

I am seeking assistance with web programming for a school assignment. My professor has outlined specific requirements for the structure of the website. One of these requirements is that the site must be XHTML compliant (Strict or Transitional). Additionall ...

Integrating Excel into a webpage - is it possible?

Currently facing an issue on my website. I'm trying to open a 'file://' URL directly with the <a href=""> element in a browser, but it's prohibited. I'm searching for a plugin or similar solution that can enable me to execut ...

A guide on navigating to a different component in Vuejs using a link

<div class="enterprise-details" style="margin-top: 20px"> Already signed up? <a href="#"> LOGIN</a></div> <!-- Component for redirection --> <b-button v-if="!registeredUser" class="button-self" v-b-modal.modal-x>Lo ...

Adjust your path by 45 degrees

I'm facing a challenge in getting all three of my images to fly off the screen in different 45-degree directions. Currently, they are all flying off the screen to the left, but I would prefer them to go in 45-degree angles. I've shared the CSS, H ...

What are the best techniques for centering a prime ng form both vertically and horizontally?

I am currently using prime ng 9.1.3 along with primeflex 1.3.0 in my project. Despite applying p-align-center, I am facing difficulty in vertically and horizontally centering the form on the screen when using a full screen height of 100vh. <div class=&q ...

The authentication callback function fails to execute within Auth0 Lock

I'm having an issue with logging into my application using Auth0. I have integrated Auth0 Lock version 10.3.0 through a CDN link in my project and am utilizing it as shown below: let options = { disableSignupAction: true, rememberLastLogin: f ...

A guide on adding up all the values in a table's columns with JavaScript

I have implemented a web application feature where table rows are dynamically added using JavaScript. Each row contains a Qty Col, Unit Amount Col, and Line Total Col. Users can also remove a line after adding it to the table. In this scenario, I need t ...

Stunning CSS Image Showcase

When hovering over my image gallery, it works fine. However, I would like the first image in the gallery to automatically appear in the enlarged section instead of displaying as a blank box until hovered over. <!DOCTYPE html> <html lang="en"> ...

Animate an image element to smoothly slide in from the left while simultaneously fading into view using Javascript

I'm looking to achieve a specific effect using pure JavaScript, HTML, and CSS without the need for jQuery or other libraries. I want an element to fade in and smoothly move to the center of the page from the left after a button click event. My attemp ...

AngularJS encountering unresponsive resources

When setting up my Angular App, I include various resources like this: angular.module('myApp', ['infinite-scroll', 'chieffancypants.loadingBar', 'ngResource']) Next, in the html file: <script type="text/javascr ...

"Sending data from client-side with AJAX to server-side PHP, processing

I'm facing an issue while attempting to send an ajax request to a php script. The php script utilizes curl to fetch data from an rss feed, and then passes that data back to the function. However, I keep encountering the following error: "Warning: W ...

Strange occurrences observed in the functionality of Angular Material Version 16

Encountered a strange bug recently. Whenever the page height exceeds the viewport due to mat-form-fields, I'm facing an issue where some elements, particularly those from Angular Material, fail to load. Here's a GIF demonstrating the problem: GI ...

The utilization of the <span> tag featuring a {float:right] property causes container expansion in Internet Explorer 7

Within my HTML code, I have an A tag button that contains a Span element to hold icons. This setup functions correctly in most browsers, except for IE7. When I attempt to float the Span to the right side using CSS, it causes issues specifically in IE7, cau ...

Setting up Karma configuration to specifically exclude nested directories

When unit testing my Angular 2 application using Karma, I encountered an issue with my directory structure: └── src/ ├── index.js ├── index.js.text ├── index.test.js ├── README.txt ├── startuptest.js ...

Avoiding the utilization of automatically generated JSON files as a data source in Rails when

I have implemented javascript code that uses JSON to generate a timeline. The JSON is being created using json_builder and it contains only the current user's information. The JSON displays correctly when accessed directly through its URL, but when th ...

Unique trigger for clicking events with customizable widgets in JQuery

I'm in the process of developing a jquery widget that functions similarly to a menu bar, featuring two buttons - ButtonOne and ButtonTwo. With my HTML code and associated styles in place, I've been focusing on creating a "hello world" widget. / ...