javascript conceal a div when clicked elsewhere

I am trying to implement two JavaScript functions: 1) Displaying a DIV (welcomeDiv) when clicking on a button; 2) Hiding the div by clicking outside of 'welcomeDiv' container.

 function showDiv() {
        document.getElementById('welcomeDiv').style.display = "block";
        }

 function hideDiv() {
        document.getElementById('welcomeDiv').style.display = "none";
        }

While both functions are functional, I am facing an issue where 'welcomeDiv' is being hidden even when clicked inside it, as it is part of the container DIV. To resolve this, I need to disable the hideDiv() function when a click occurs inside 'welcomeDiv'. I have attempted something like:

<div id='welcomeDiv' onclick='hideDiv().disable'>

However, I have been unsuccessful in writing the code correctly despite trying various methods. Any help or suggestions would be greatly appreciated. Thank you in advance.

Answer №1

Here is a simple HTML file showcasing a solution:

<html>
    <head>
        <title>Test</title>
        <style type="text/css">
            .container { width: 400px; height: 280px; background-color: #e5e5e5;}
            #welcomeDiv { width: 100px; height: 100px; background-color: #b0b0b0; }
        </style>
    </head>
    <body>

        <div class="container" onclick="hideDiv();">
            <button onclick="showDiv();">
                Hello
            </button>

            <div id="welcomeDiv">
                <h1>Welcome</h1>
            </div>
        </div>

        <script type="text/javascript">
            function showDiv() {
                document.getElementById('welcomeDiv').style.display = "inherit";
                event.stopPropagation();
                // stop propagation on button click event
            }

            function hideDiv() {
                var target = event.target || event.srcElement;
                // filter event handling when the event bubbles
                if (event.currentTarget == target) {
                    document.getElementById('welcomeDiv').style.display = "none";
                }

            }
        </script>
    </body>
</html>

Answer №2

It could be a possibility:

<div id='welcomeDiv' onclick='showDiv()'>

Answer №3

To determine what has been clicked, access the JavaScript 'event' object. This object contains information regarding the event that occured, such as a 'MouseEvent'. Utilize this data to identify the clicked element by examining the 'target' property. Assign an ID to your containing DIV for better click filtering:

HTML:

<div id="welcomeContainer" onclick="showDiv(event)" style="border: 3px solid red;">
Outer Div
<div onclick="hideDiv(event)" id="welcomeDiv" style="border: 3px solid blue;">Inner Div</div>

JavaScript:

function showDiv(event) {
    if(event.target.id === "welcomeContainer"){
        document.getElementById('welcomeDiv').style.display = "block";
    }
}

function hideDiv(event) {
    document.getElementById('welcomeDiv').style.display = "none";
}

Check out this working code demonstration on Fiddle: http://jsfiddle.net/fmz2h6kj/

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

Determine the total number of rows present in a Selenium web table

I have a web table in a page that only has one attribute, which is the class. I am trying to determine the number of rows in this table. The code below works, but it provides me with the count of all web tables that have their parent class set as OverviewT ...

Exploring schema.org itemref inquiries

I am currently working on implementing microdata (schema.org) on a website dedicated to a software application. To avoid duplicating code, I am trying to add metadata only once and then reference it throughout the site. However, I have a question regardi ...

Looking for assistance with React - Can anyone help get this up and running?

Recently, I came across an exquisite design created by Sean on Codepen. Sean utilized React to craft this captivating horizontal accordion. The code snippet can be found below, or you can visit the Codepen link if you wish to fork it. However, I'm e ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

an issue encountered while trying to print a webpage styled with CSS

Users are given the option to print the current page on the website by clicking on a menu element: <li> <a href="#" onClick="window.print()"> <i class="icon-print"></i> Print Page </a> </li> The page contai ...

My XSLT document is not converting to valid HTML code

As a beginner, I've recently taken up XML and XSLT. A task was assigned to me to create an XSLT file based on the XML snippet provided below. <?xml version="1.0" encoding="UTF-8"?> <event> <title>Test 1</title> <descript ...

Using Reactjs: How do you insert HTML code into the primaryText of a list item?

Is it possible to include a span element inside a ListItem like so: <ListItem primaryText={"<span class='inner'>Some important info</span>" + item.title} /> When I view the rendered content, the output is not an HTML span ...

jQuery conceal input field after it has been displayed

I've created an HTML form with two different sections for search purposes. The first section displays basic fields, and by clicking on "Advanced Search" (in my case, "Расширенный поиск"), additional fields are revealed. Everything work ...

Deleting Empty Session Data

I have set up sessions for my website. In order to initialize the session, I included the following code on every link of the website: session_start(); if(isset($_SESSION['User'])) { //session_start(); $sesvar = $_REQUEST['sid']; } ...

Unable to conceal a DIV using React

I'm attempting to hide a div programmatically upon clicking a button. I've written the following code, but it doesn't seem to be working (the Div remains visible): import React, {useState} from 'react'; import './Button.css&ap ...

Filter search results to display only posts

My website uses a custom Wordpress theme that has a search functionality. The issue I'm facing is that when I perform a search, it redirects me to the search.php page. However, instead of just displaying posts, it also shows pages and events from the ...

Issue with Ajax not triggering PHP script

My first experience with using Ajax to call a php script is not going well. The script doesn't seem to be working at all. Here is the snippet of code where I implemented Ajax: <?php if (isset($_GET['error'])) { switch ($_GET[ ...

How can I center <text> within a button using Vue Native?

Is there a way to position the "login" text in the center of the button? I've attempted using align-items: center; and justify-content: center;, but it doesn't seem to be working https://i.sstatic.net/XVHWA.png <template> <view cla ...

Saving data values for utilization in jQuery

Recently, I've come across a series of links structured like this: <a class="colorBox" href="#" title="#0676B3"></a> <a ... <a ... these links all have color values in the title attribute <a ... What I'm trying to do is uti ...

Difficulty filling height with Bootstrap 4 flex-grow

I am in need of creating a layout with a header div at the top (that can be filled with content), a footer div at the bottom, and a middle div with an adaptable height to fill the entire screen. Check out my code below: <div class="container-fluid p-0 ...

The ngMessages validation feature in AngularJS fails to remove error messages from the CSS styling

Can anyone help me figure out why I keep getting a red color underline error even though there is no actual error and validation is successful? https://i.sstatic.net/AESLl.png I created my own directive to validate passwords and I am using Angular materi ...

There seems to be an issue with the syntax in ReactJS: the URL is

I'm facing an issue in my React code. I have a function that doesn't seem to be in the correct format for React. check(img) { console.log(img,typeof img) const url=""; const arrN = ["15","16","35","36","37","38","39","40" ...

Combine strings in an array of objects

I have an array containing objects with a "Closed" property that holds numerical values. I want to loop through the array and concatenate all the "Closed" property values found in each object. For example, in the given array, the final result should be 12 ...

The parameters passed in an axios get request are not carried over to a create request

Exploring the capabilities of the YouTube API with ReactJS While working with the YouTube API, I came across the create method in axios. However, I faced an issue where the params were getting overwritten. What am I missing here? I have a file named yout ...

Identifying input fields using XPath depending on their associated labels

I'm trying to figure out why an XPath query I found returns multiple results when selecting an input based on its label. The first XPath query I used, //input[@id=(//label[.='Max Driving Time_h']/@for)], retrieves 3 inputs even though only o ...