Adding hover CSS attributes via jQuery/Javascript

75,522

Solution 1

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");
});

Solution 2

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()

Solution 3

You should put them in a hover event:

var elem = $('#elem');

elem.hover(function () {
    // ... :hover, set styles
}, function () {
    // ... this function is called when the mouse leaves the item, set back the
    //     normal styles
});

However, I completely recommend to put your CSS in classes and use those classes in JS, you should split the languages as much as you can.

Solution 4

$("#someObj").hover(function(){
    $(this).css(...);
}:);

http://api.jquery.com/hover/

Share:
75,522
Nyxynyx
Author by

Nyxynyx

Hello :) I have no formal education in programming :( And I need your help! :D These days its web development: Node.js Meteor.js Python PHP Laravel Javascript / jQuery d3.js MySQL PostgreSQL MongoDB PostGIS

Updated on March 21, 2020

Comments

  • Nyxynyx
    Nyxynyx about 4 years

    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') }
    )
    
  • Anthony Grist
    Anthony Grist over 11 years
    Care to elaborate on the "There's more control" statement? As far as I'm aware the .hover() function is just a shorthand for doing precisely what you've coded.
  • Jon
    Jon over 11 years
    I just like the explicitness of it saying 'mouse entering the element' and 'mouse leaving the element'. However, the graphs on this page would suggest that live mouseenter/mouseleave is the best in terms of optimization. jsperf.com/hover-vs-mouseenter
  • Moss
    Moss about 10 years
    This causes the css to stick after you move the mouse away.
  • Mickey Vershbow
    Mickey Vershbow over 2 years
    @Jon great answer, very useful thanks. One quick thing, you forgot the "#" hash symbol on the hex color code for the mouseleave function, which is required for that bit of code to work.