CSS :hover activates only when the mouse is in motion

Looking at a simple example I put together:

HTML

<div id="sample"></div>

CSS

#sample {
    width:400px;
    height:400px;
    background-color:green;
    display:none;
}

#sample:hover{
   background-color:red;
}

It's a hidden DIV that changes color on hover.

After 2 seconds, JavaScript reveals it:

setTimeout(function() {
     document.getElementById('sample').style.display="block";
},2000)

If the mouse is over the area where the DIV will appear before it does so, it won't show the hover effect until you move the mouse. See a demo here.

Is this intentional? Is there a way to detect if the DIV is hovered without using JS?

Answer №1

Although the opacity property can be used, as mentioned by @BrianPhillips, it may not function properly in IE 8. If you're looking for a workaround that involves Javascript, here's a concise solution:

window.onmousemove=function(event){
    ev = event || window.event;
    if (event.pageX <= 400 && event.pageY <= 400){
        document.getElementById('bla').style.backgroundColor= "red";
    } else {
        document.getElementById('bla').style.backgroundColor= "green";
    }
}
setTimeout(function() {
     document.getElementById('bla').style.display="block";
},2000)

Check out the demo here

Answer №2

By setting the display to none, you are essentially removing the image from the layout, which means there is no area to hover over.

To work around this issue, you can set the background-image in your CSS to rgba(0 0 0 0); This will make the image invisible while still maintaining its presence in the DOM. You can then update your JavaScript code to:

setTimeout(function() {
     document.getElementById('bla').style.backgroundColor="green";
},2000);

Check out this JSFiddle for reference.

Answer №3

If you want to control the visibility of an element without affecting the flow of the page, one option is to use CSS opacity and set the position to absolute. This method seems to be effective:

CSS:

#example {
    width:250px;
    height:250px;
    background-color:blue;
    opacity: 0;
    position: absolute;
}

JS:

setTimeout(function() {
         document.getElementById('example').style.opacity="1";
         document.getElementById('example').style.position="relative";
},2000)

Demo

It's worth noting that using opacity allows elements to respond to events like click or hover, unlike elements with visibility: hidden or display:none. (source)

Keep in mind that opacity may not be supported in IE 8 and earlier versions.

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

Error message: 'Encountered issue with react-router-V4 and the new context API in React

Currently, I am experimenting with the integration of React Router V4 alongside the new React context API. Below is the code snippet I am working with: class App extends Component { static propTypes = { router: PropTypes.func.isRequired, ...

Utilize DataTables with a custom search form for enhanced data filtering

I rely on DataTables for its advanced functionality in creating tables with paging capabilities. When submitting data through a standard jQuery Ajax request using my own form, the returned data is formatted and then passed to the DataTables function to en ...

Updating model values while dragging with Angular Dragular

Currently, I am experimenting with dragula and its newer version, dragular, on some sample projects. One specific dilemma I am facing involves the implementation of drag and drop functionality in an Angular project. My query pertains to utilizing a list o ...

Error during live-server npm installation: symlink issue persists even with root/admin privileges

In my current project, I am following a tutorial on AngularJS from the book titled "Unraveling AngularJS 1.5 (With Over 130 Complete Samples" by István Novák, which stipulates the need for installation of Node.js. The appendix of this book provides comma ...

A guide on automating the html5 color picker using input type="color" in selenium webdriver

When interacting with an HTML color input element, a color picker window pops up that prevents viewing the DOM. I am looking for a solution to either select a color and close the window or enter a hex code in the popup's text box. Can anyone provide m ...

Add text to the forefront of video content while in fullscreen mode

Currently, I am facing an issue while trying to embed a video from YouTube. I am unable to draw anything (text, image, etc.) when the video is in fullscreen mode. Despite my attempts to use z-index, it has not been successful. My goal is to create a n ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

The webpage continues to refresh after executing a JavaScript function triggered by the AJAX response

I have experimented with various solutions for calling a JavaScript function returned from an AJAX response. While each method worked to some extent, I found that using an alert within the refreshResults function was necessary in order to display the resul ...

Discover the art of utilizing two distinct binding strings, wherein upon the selection of either, the alternate binding string shall automatically be

Having to use two different bindingstrings is a requirement due to a tool used for creating PDFs. My objective is to have the corresponding bindingstring turn "Off" when a user clicks on either the Yes or No button, and have the clicked button turn to "Yes ...

Content located on the right-hand side of the menu

I am currently working on a vertical navigation menu design, but I am facing some issues with aligning the text to start from the very left edge of the element. HTML <div class="jobs-links"> <ul> <li><a href="renovations. ...

What is the best way to adjust the maxHeight within AccordionDetails and enable scrolling functionality?

I am looking to display a large amount of data using the Accordion component from material-ui nested inside a Box element. However, I am unsure how to customize the default styles in order to set a specific maxHeight. Is there a way for me to take control ...

Vue Router generates a URL containing %2F when dealing with slug routes

I am facing an issue in my Vue 3 application where I need to create a route for dynamic slugs. Currently, when using RouterLink, the generated URL contains %2F instead of actual slashes which is not the desired result. For example, the current URL looks l ...

What is the best way to implement the 'setInterval' function in this code to effortlessly fetch forms or data on my webpage without any need for manual refresh?

I am using ajax and javascript to fetch a modal on another page or in a separate browser. While I am able to retrieve the modal, I require the page to refresh before displaying the modal. I have come across suggestions to use the setInterval function but I ...

Faux CSS, every other moment appears to be unsuccessful

My HTML code looks like this: <div class="container"> <div class="foo">Foo!</div> <!-- if this is red... --> <div class="bar">Bar!</div> </div> <div class="container"> <div class="foo">Foo! ...

An issue occurred with the session being undefined in Node.js Express4

I'm encountering an issue where my session is undefined in new layers even after setting the value within an "if" statement. /*******************************************/ /**/ var express = require('express'), /**/ cookieParse ...

Ways to format table using flex-wrap sans the use of flexbox

My HTML and CSS structure is as follows: .item { background: white; padding: 5px; display: inline-block; text-align: center; } .item > div { background: yellow; width: 60px; height: 60px; border-radius: 50%; display: table-cell; ...

Filter array to only include the most recent items with unique names (javascript)

I'm trying to retrieve the most recent result for each unique name using javascript. Is there a straightforward way to accomplish this in javascript? This question was inspired by a similar SQL post found here: Get Latest Rates For Each Distinct Rate ...

Identifying and stopping sluggish third-party JavaScript requests

Our website utilizes various Tracking Pixels to collect data on our visitors. However, at times the third-party JavaScript embedded in our code is waiting for a response from their server. If their server fails to respond properly, it can lead to error mes ...

Tips for displaying user-entered information from a form after submitting it with PHP

How can I display the email in the email text input field with this code? It doesn't seem to work correctly when there is a failed login attempt. value= "if(isset($_POST['submit'])){ ?PHP echo $_POST[''email']?>"; ...

What is the process for displaying HTML page code received from an AJAX response?

My current project involves implementing JavaScript authentication, and I have a specific requirement where I need to open an HTML file once the user successfully logs in. The process involves sending an AJAX request with the user's username and passw ...