Using Javascript to display a Div element for a short period of time when the mouse is clicked

Having some trouble creating a hidden colored block that appears after a mouse press anywhere on the page, stays visible for 2 seconds, and then disappears until another mouse press triggers it again. I've tried using '.click(function' and other methods without success.

My current setup involves a DIV layer like this...

HTML:

<div class="overlay"></div>

CSS:

.overlay {
position: absolute; 
z-index: 1000;
right: 240px;
top: 500px;
width: 1000px;
height: 100px;
background: rgba(255, 255, 200, 100);
}

As a newcomer to javascript, any guidance on how to achieve this would be greatly appreciated.

Answer №1

To achieve this effect in jQuery, you can utilize the setTimeout function.

$( "#target" ).on( "click", function() {
  $("#messageBox").hide().slideDown();
  setTimeout(function(){
      $("#messageBox").hide();        
  }, 2000);
});
#messageBox {
    display:inline-block;
 float:right;
 border:1px solid #060;
 background:#FFC;
 padding:10px 20px;
 box-shadow:2px 2px 4px #666;
 color:#060;
 font-weight:bold;
 display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="messageBox">
  Hi there.
</div>
<input type="button" id ="target" value="click"/>

Answer №2

Using jQuery(document) instead of targeting a specific place on the page allows the click event to be triggered for the entire document.

jQuery(document).click(function(event) {
    var $div = $(".overlay");
    if ($div.is(":visible")) { return; }
    $div.show();
    setTimeout(function() {
        $div.hide();
    }, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

By utilizing jQuery(document), there is no need for a specific target div or element to trigger the click event. This allows the event to be fired on the entire document.

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

Which approach is more impactful: consistently sending an ajax request or breaking down the result within a function?

My JSON data consists of news entries with titles, text, and dates. Here is an example: { "news": [ {"title": "some title #1","text": "text","date": "27.12.15 23:45"}, {"title": "some title #2","text": "text","date": "26.12.15 22:35"}, ... ...

State remains stagnant following update from use state

Recently diving into React, I've been experimenting with getting my socket io listener up and running smoothly. Interestingly, when I have it placed outside of the useEffect, it seems to function but gets called multiple times. However, when nestled w ...

The asynchronous ajax request is leading to a browser freeze

In the HTML page, I have two sets of a and p elements that are initially set to display:none. At the bottom of the page, there is a function being called with their respective ID's and values, which will enable one of them based on certain conditions ...

How to align button text and other ion-col text at the bottom in Ionic 2

Here is the code snippet I am working with: <ion-row><ion-col ><button ion-button outline no-padding large (click)="setUserName()">D</button>ay in the life </ion-col></ion-row> I find the layout unattractive as the le ...

Learn the ins and outs of utilizing *ngIf in index.html within Angular 8

Can anyone explain how I can implement the *ngIf condition in index.html for Angular2+? I need to dynamically load tags based on a condition using the *ngIf directive, and I'm trying to retrieve the value from local storage. Below is my code snippet b ...

NPM TypeORM is throwing the error message "Duplicate migrations" when changes are made to a migration file

Recently, I made a modification to an existing table by adding a new column using the command npm run migration:generate <filename>. Unfortunately, I realized later on that I had misspelled the column name and needed to correct it (showComission -&g ...

What is the best way to fill the dropdown options in every row of a data table?

This HTML snippet displays a data table with test data and corresponding dropdown options. <tr> <th> Test Data </th> <th> Test Data ...

Encountering the error `ReferenceError: document is not defined` when trying to deploy a Next.js project on Vercel

I recently worked on a Next JS project and deployed it to Vercel. Initially, everything was running smoothly, so I didn't check the website status for a while. I was just developing it locally and pushing updates to GitHub. However, when I finally rev ...

Looking to replace an existing class with a new one in a div element?

I have developed a form builder where selecting a value option from 1 to 12 will append a col-xs-(1-12) class to a div. However, I am facing an issue where choosing a different option does not remove the previously added class. function addGrid() { ...

Creating unit tests for linked functions in Node.js using Jest

Hey there! I'm looking to test a function using Jest that involves token verification and requires 3 parameters. Here's the code for the function: const verifyToken = (req, res, next) => { // Checking for token in header or URL parameter ...

Tips for loading images in advance while looping through an array for background images

Looking for a solution to an issue with a simple loop that is cycling through a set of images in an array and setting them as the background-image property of an element. The problem arises because the images are loading, causing the animation to act errat ...

Why do all the select boxes require two clicks to open the drop-down menu when the function is activated?

After implementing this code on my webpage, I noticed an issue where all select boxes required two clicks from the user to open the drop-down menu. The first click seemed to set focus on the box, and only on the second click would the drop-down actually ap ...

I'm having trouble applying JavaScript to my Flask template, even though it is stored in the static directory. Any suggestions on how to fix this issue with the code provided?

I am currently working on a Flask project and attempting to create a hierarchical structure resembling a tree. However, I suspect that the JavaScript is not being correctly applied to my tree.html file, as the options cannot be expanded. The code provided ...

Generating a fresh PHP webpage through the administration dashboard

Currently, I am working on developing a blog page using PHP. One key aspect that I am struggling with is figuring out how to efficiently create new posts from the admin panel. Any suggestions or advice would be greatly appreciated! ...

update the dropdown values in the database by submitting the form

Members sign up for the website. The administrator will log in and access a list of users. I am attempting to provide an option for the admin to select a checkbox and update the user's status through a dropdown menu submission. When I tested the code ...

Display a single qTip tooltip on click, toggling between different tooltips as needed

I am currently working on implementing qTip2 for displaying an HTML content tooltip when a link with the class "bb" is clicked. The goal is to have the tooltip open the div with the class 'tooltiptext' when a link with class 'bb' is cli ...

Changing Float Attributes to String in Google Earth Engine

I am trying to export data from Google Earth Engine to my Google Drive. To name the file, I am using information from its data properties which results in 2019.0_1.0. However, I would like the file name to be in a different format - '2019_1'. Bel ...

"Creating a dynamic dropdown menu and sub-menu in PHP using MySQLi with unique slug values

I need to generate a dynamic menu from the database, including main menus and submenus. For instance: <li class="<?= ($pg == 'departments') ? 'active':''; ?>"> <a href="departments">Departments</a> ...

The Importance of Apostrophes when Working with XML and Data-Bound Controls

Within my XML content, there may be instances where an apostrophe appears in a node's value: <Root> <Sections> <SectionA> <Heading>Title</Heading> <Description>This is section &a ...

Real-time collaborative Whiteboard using WebSocket technology (socket.io)

I am currently working on developing a collaborative online whiteboard application using HTML5 canvas, Node.js, and Websockets (Socket.io). While my progress is going well, I am facing some challenges when it comes to drawing circles. I have been successfu ...