Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding hover CSS attributes via jQuery/Javascript

Some CSS styles need to be applied to an element on hover, and CSS styles have to be applied using javascript/jquery directly and not through stylesheets or $(this).addClass('someStyle') because I am injecting the DOM elements into another page.

We can apply the usual css styles using

$('#some-content').css({     marginTop: '60px',     display: 'inline-block' }); 

How should we add the CSS styles for :hover events?


Do we have to resort to:

$('#some-content').hover(        function(){ $(this).css('display', 'block') },        function(){ $(this).css('display', 'none') } ) 
like image 869
Nyxynyx Avatar asked Dec 04 '12 16:12

Nyxynyx


People also ask

How can get hover effect in jQuery?

The hover() is an inbuilt method in jQuery which is used to specify two functions to start when mouse pointer move over the selected element. Syntax: $(selector). hover(Function_in, Function_out);

How do you hover in Javascript?

The 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.

Is hover deprecated in jQuery?

hover() is deprecated #66.

How do I enable hover in CSS?

The :hover selector is used to select elements when you mouse over them. Tip: The :hover selector can be used on all elements, not only on links. Tip: Use the :link selector to style links to unvisited pages, the :visited selector to style links to visited pages, and the :active selector to style the active link.


2 Answers

I find using mouseenter and mouseleave to be better than hover. There's more control.

$("#somecontent").mouseenter(function() {     $(this).css("background", "#F00").css("border-radius", "3px"); }).mouseleave(function() {      $(this).css("background", "00F").css("border-radius", "0px"); }); 
like image 113
Jon Avatar answered Sep 23 '22 01:09

Jon


Try this:

$('#some-content').hover(function(){     $(this).css({ marginTop: '60px', display: 'inline-block' }); }, function(){     $(this).css({ //other stuff }); }); 

or using classes

$('#some-content').hover(function(){     $(this).toggleClass('newClass'); }); 

More info here .hover() and .toggleClass()

like image 30
Mark Walters Avatar answered Sep 23 '22 01:09

Mark Walters