Display a block by using the focus() method

My objective is :

  • To display a popin when the user clicks on a button
  • To hide the popin when the user clicks elsewhere

I previously implemented this solution successfully: Use jQuery to hide a DIV when the user clicks outside of it

However, I wanted to experiment with something new, so I decided to try using focus()

Here is the code I came up with :

div
{
  width: 100px;
  height: 100px;
  border: 1px solid blue;
}

div:focus
{
  background-color: red;
}
<script>
function show()
{
document.getElementById("element").focus();
}

</script>

<input type="button" onclick="show()" value="click me!"/>
<div id="element"tabindex="-1">

</div>
After clicking the button, click elsewhere to remove the red background

This approach worked well, but now I want to toggle the block's visibility by clicking the button. The only difference between the two versions is that I added display: block and display: none

div
{
  width: 100px;
  height: 100px;
  border: 1px solid blue;
  display: none;
}

div:focus
{
  background-color: red;
  display: block;
}
<script>
function show()
{
document.getElementById("element").focus();
}

</script>

<input type="button" onclick="show()" value="click me!"/>
<div id="element"tabindex="-1">

</div>

Unfortunately, this modification is not working as expected. Can anyone help me understand why?

Answer №1

An object with the CSS property display: none cannot be focused on.

This quote is from a discussion on Stack Overflow:

If an element is not visible, it cannot receive focus, which means the :focus pseudo-class will not work on it.

Answer №2

To implement this functionality using CSS, you can take advantage of the adjacent sibling selector. Simply put, when the button is focused, the adjacent div element will become visible:

div {
  width: 120px;
  height: 120px;
  border: 2px solid green;
  display: none;
}

button:focus + div {
  background-color: yellow;
  display: block;
}
<button type="button" value="">click here!</button>
<div id="content" tabindex="-1"></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

What is the most effective way to transfer color values from one div to another?

When recreating a game similar to Mastermind, I encountered a challenge of copying color values from one div to another upon clicking a button. Despite browsing the web, I haven't found a solution for this specific situation. Below is the code I have ...

ng-if directive does not show data in AngularJS

I have a dynamic collection of images and videos that I want to display one at a time. Specifically, when I click on an image ID, I want it to show the corresponding image, and when I click on a video ID, I want it to show the relevant video. Below is the ...

HTML5 header video with a subtle color palette

Is there a way to insert a muted video in the header that spans the full width but only has a height of 300px? The issue I am encountering is that when I decrease the height of the video, the width automatically decreases as well. However, what I want is ...

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...

The contenteditable attribute does not function properly in a foreignobject element on Firefox browsers

<?xml version="1.0" standalone="yes" ?> <svg xmlns="http://www.w3.org/2000/svg"> <foreignObject width="100" height="100" x="20" y="65"> <body xmlns="http://www.w3.org/1999/xhtml"> <p contenteditable="true">text&l ...

Printing specific div content from an HTML page using a print button

I have a situation where I need to control the printing functionality of my HTML page. Currently, I have two div tags in my code with a single print button at the top of the page. When I click on this button, it prints the content from both divs. However ...

Copying Objects in JavaScript Using Deep Cloning

My current project involves using Nodejs to create a deep copy of an object generated by Squel, a query building library. The main dilemma lies in how to replicate the exact filteredQuery variable. The object is initialized with: filteredQuery = squel.sel ...

Creating a personalized message for a failed "Get" request using the HTTPS native module in combination with

Currently, I have implemented an Express application that includes an HTTP GET request to an external API. It functions properly when there are no errors; however, I am looking to customize the response sent to the client-side in case of failures: const ht ...

Limiting the displayed portion of a table and implementing scrolling instead

I am currently working with a static HTML template that contains the following code: <table> <thead></thead> <tbody></tbody> </table> Using jQuery and AJAX, I am dynamically adding and removing rows and columns ...

Is there a way to easily toggle a Material Checkbox in Angular with just one click?

Issue with Checkbox Functionality: In a Material Dialog Component, I have implemented several Material Checkboxes to serve as column filters for a table: <h1 mat-dialog-title>Filter</h1> <div mat-dialog-content> <ng-container *ng ...

Incorporating additional ES6 modules during the development process

As I build a React component, I find that it relies on an ES6 component that I'm currently developing. Since I created the latter first, what is the typical method to include it during development as I work on the second component? If the dependency w ...

Share edited collection with Observer

The challenge Imagine creating an Angular service that needs to expose an Observable<number[]> to consumers: numbers: Observable<number[]>; Our requirements are: Receive the latest value upon subscription Receive the entire array every tim ...

What is the inner workings of stream.Transform in Node.js?

Recently, I stumbled upon a code snippet on a blog showcasing the usage of the stream Transform class to modify data streams and display the altered output. However, there are certain aspects of this code that leave me puzzled. var stream = require(&apos ...

The IE browser consistently retrieves outdated data from its cache

I always encounter the issue of IE browser loading old data from the browser history. To ensure that I am getting the latest data, I consistently need to clear the browser history. Is there a way to consistently load new data without having to manually cl ...

Instructions for sorting an array of objects by Firebase Timestamp

I am looking for a way to order my messages based on timestamp in Firebase v9. In earlier versions, I was able to do this but now I seem to be facing some difficulties. Here is the data structure set up on Firestore: const [messages, setMessages] = useSta ...

Why does the for loop assign the last iteration of jQuery onclick to all elements?

I've encountered an issue with my code that I'd like to discuss var btns = $('.gotobtn'); $('#'+btns.get(0).id).click(function() { document.querySelector('#navigator').pushPage('directions.html', myInf ...

Why doesn't jQuery UI's addClass method animate visibility like it should?

One of the advantageous features of jQuery UI is its enhancement of the jQuery addClass method, which enables animation by including a second parameter for 'duration', as shown below: $('div').addClass('someclass', 1000); Th ...

ng-click="showInventory()" onClick="currentTemplate='/inventory.html'" Not

I'm facing an issue with my menu list. When I apply the ng-repeat directive, it seems to not work properly. However, when I remove the ng-repeat, everything functions as expected. <div class="reports_header_tabs_holder"> <span ng-repea ...

What is the method for determining the level based on the provided experience points?

I've created a formula that can calculate experience based on specific levels and another formula that calculates the level based on given experience. However, there seems to be an issue with the second function as it is not returning the expected val ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...