Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a css ":hover" on a DOM created element in JavaScript?

I'm using the DOM to manage a JSON response from an AJAX function I'm running. The script I'm writing needs to be completely portable, so I am defining the styles for the created elements on the fly (meaning, no linking to an external CSS, and no providing CSS in the HTML doc itself, because I won't have control of the doc).

I'd like to create a hover effect on some of the elements.

example:

 #myDiv:hover { background:#000000; }

Is there a way to define that in the DOM? Or do I have to use mouseover?

like image 487
johnnietheblack Avatar asked Apr 03 '09 16:04

johnnietheblack


People also ask

Can we use hover in JavaScript?

jQuery hover() MethodThe hover() method specifies two functions to run when the mouse pointer hovers over the selected elements. This method triggers both the mouseenter and mouseleave events. Note: If only one function is specified, it will be run for both the mouseenter and mouseleave events.

Can you put a hover on a div?

To display div element using CSS on hover a tag: First, set the div element invisible i.e display:none;. By using the adjacent sibling selector and hover on a tag to display the div element.

Can CSS modify Dom?

No, CSS does not change the DOM.


2 Answers

You can dynamically create and manipulate stylesheets. See here for some of the cross-browser issues with this approach.

I've got a wrapper function lying around which works around some of them; using it, the code would read

document.createStyleSheet().addRule('#myDiv:hover', 'background:#000000;');
like image 154
Christoph Avatar answered Sep 29 '22 03:09

Christoph


you may create element with predefined class:

.h:hover{color: #c00}

var elem = document.createElement('div');
elem.className = 'h'
like image 29
Sergei Kovalenko Avatar answered Sep 29 '22 03:09

Sergei Kovalenko