Clicking outside the box will close it

I received a code from the internet that allows me to click on text and open a box.

However, I am looking to add functionality to close the box when I click outside of it.

Here is the javascript code I am using:

function setVisibility(id, visibility) {
document.getElementById(id).style.display = visibility;
}

Here is the corresponding HTML code:

<div value='Show Layer' onclick="setVisibility('sub2', 'inline');">
  <span>SHOW BOX</span>
</div>

<div id="sub2">
  <p>This is a test for the box.</p>
  <button value='Hide Layer' onclick="setVisibility('sub2', 'none');" ;>Click to close the box</button>
</div>

And here is the CSS code I have implemented:

 #sub2 { width: 500px; color: black; display: none; background:#eeeeee; display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 1; overflow: auto; / }
 #sub2 h5 { font-family: 'Varela Round', sans-serif; font-size:20px; }

Answer №1

implement the onfocusout method in JavaScript

Here's an example:

<script>
document.getElementById("BOXID").addEventListener("focusout", myFunction);

function myFunction() {
    document.getElementById("BOXID").style.visibility='hidden';
}
</script>

PLEASE NOTE: Replace BOXID with the specific ID of the box you wish to close

Further reading: Tutorial: onfocusout Event

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

The component is unable to retrieve the state stored within the store

I've encountered an issue with my Array component not being able to access the state "count" stored in a Redux store. I've double-checked that the store is connected and it appears in the React dev tools. The Array component is supposed to take t ...

Jquery and adaptability

I currently have a scrollTo anchor link script on my website that has an offset of -35px to account for my 35px high navigation bar. However, I find that this offset may need to be adjusted for different screen resolutions, such as smartphones or tablets ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Drop-down options disappear upon refreshing the page

Code snippet for sending value to server using AJAX in JavaScript In my script, the status value may vary for each vulnerable name. When selecting a status option and storing it in the database through AJAX, the selected value is lost after refreshing th ...

implementing a timestamp in a specific timezone with Vue.js

Utilizing a timestamp attribute, I have successfully implemented the display of the current time and date on my webpage. Is there a way to showcase this information in a specific time zone? I am looking to present it in the ZULU timezone, which remains st ...

What is the most efficient method for linking the hostname of my website to the file path within my Express.js static file server?

When using vanilla JavaScript in the browser, we can retrieve the hostname using: window.location.hostname However, if we are working with Node.js/Express.js on the server side, how can we achieve the same result? Furthermore, I am looking for a way to ...

The dichotomy between public and private methods within a Vue.js component

Within a component, I have two functions defined. One is foo(), which is defined within <script>, and the other is fooExported(), which is defined in the body of export default {}. My understanding is that functions inside export default {} can be a ...

The next and previous buttons on the JQuery UI datepicker are related to only one ancestor. When using $(e.target).parents(), it will only return a

Unfortunately, my reputation isn't high enough to post my own answer just yet. However, I wanted to share it before wasting more people's time: I finally figured out why I was not getting all the expected ancestors: The JQuery datepicker actuall ...

CSS3 animations can sometimes result in incorrect element sizing due to the animation-fill-mode property

After experimenting with CSS3 animation, I encountered an unusual issue. Adding animation-fill-mode to the "parent" <div> caused the width of the "child" <div> to be less than 100% upon completion of the animation. Can anyone shed light on why ...

The task "gulp js src - duplication and implementation of base" involves duplicating

My gulp task is set up to copy JavaScript files. The initial setup below did not work: gulp.src('./**/*.js', {base: '../src/main/'}) .pipe(gulp.dest('../target/dist')); After making some adjustments, the following code ...

Can you explain the exact meaning of XMLHttpRequest.XMLHttpRequest?

I find MDN's writing style to be confusing. On the MDN page about XMLHttpRequest, it states: XMLHttpRequest is an API ... Constructor XMLHttpRequest.XMLHttpRequest Properties XMLHttpRequest.onreadystatechange XMLHttpRequest.readyState XMLHttpReq ...

Diving into Discord.JS - Is there a way to check if a specific message content exists within an array?

I'm currently working on developing a Discord user verification bot that generates a 2048-bit key upon joining a server. This key will be crucial for verifying your account in case it gets compromised or stolen, ensuring that the new account belongs t ...

When utilizing the JavaScript createElement() method to create elements on keydown, it will not be compatible with jQuery's draggable() method

I'm currently developing a drag and drop feature for a project, allowing users to add items to a work area and then position them by dragging. I'm facing an issue where I want to create multiple instances of the same element using a key code, but ...

I am trying to retrieve the class name of each iframe from within the iframe itself, as each iframe has a unique class name

My index HTML file contains multiple Iframes. I am trying to retrieve the class names of all iframes from inside an iframe. Each iframe has a different class name. If any of the iframes have a class name of 'xyz', I need to trigger a function. I ...

AngularJS, building a hash of resources

Is there a way, in an AngularJS controller, to take a URL and redirect that request to the best place for fetching JSON data? The VideoSearchCtrl is connected to the search form. Everything seems fine with the generated URL for the template, so I aim to us ...

Tips on invoking a class method within lodash debounce function

Help needed: Issue with TypeError - Expected a function at debounce when calling a class method in the lodash debounce class Foo { bar() { console.log('bar'); } } const foo = new Foo(); _.debounce = debounce(foo.bar(), 300); ...

Tips for creating a scrollable smiley input field

I have a chat system where I am incorporating smileys from a predefined list. QUERY I am looking to create a scrolling feature for the smileys similar to how it is implemented on this particular website. The twist I want to add is to have this functiona ...

Guide to selecting text within an unordered list on an HTML webpage without a distinctive identifier with Python Selenium

I am looking to automate the selection and clicking of the text 'Click Me Please' within a hyperlink using Python Selenium. The main challenge is that there is no distinct identifier for this item as it is nested within a list. The specific HTM ...

Storing JSON data in list items within an HTML document using React

I am currently working on creating a component that can provide auto-suggested values from an online API and then send the value and its associated JSON data back to the parent component. So far, I have successfully implemented a feature that generates a ...

Attempting to alter the appearance of my validation control by implementing a custom style sheet theme

After naming a style sheet theme Basic and applying it to my web.config file, I created a Validator class in the css file. Utilizing the cssClass attribute with the Validator type, I successfully adjusted the font-weight property but struggled to change th ...