AlexGH
AlexGH

Reputation: 2817

mouseleave() return to before mouseenter()

is there anyway to return the elements $("p") to the exact color it had before the mouseenter() method was applied? Or do I need to know which color it was exactly before the mouseenter() and then apply that color with mouseleave()? I want it to return to the color that it had before when the mouseleave() is applied... Is there other way than knowing which color it had before mouseenter()?

Jquery code(I don't want to set it to blue, I want to set it the color it had before mouseenter()):

$(document).ready(function () {
    $("p").mouseenter(function () {
    $(this).css("color","yellow")
    })
    .mouseleave(function () {
        $(this).css("color","blue")
    })
   })

Upvotes: 0

Views: 444

Answers (5)

Alex McCabe
Alex McCabe

Reputation: 1892

First things first, if you can, you really should be using jQuery's .on(event) method. It's more consistent, easier to read and is better 'practice'. You can also namespace events using this method.

This is how I would do it, now it's re-useable on any element or class, and can be styled differently for each.

function changeColorOnHover(elementClass) {
    var $element = $(elementClass);

    $element
        .on('mouseenter', function (event) {
            // store a reference to this element
            var $this = $(this);

            $this.addClass('is-hover');
        })
        .on('mouseleave', function (event) {
            // store a reference to this element
            var $this = $(this);

            $this.removeClass('is-hover');
        });
}

Check out the pen to see it in action.

http://codepen.io/alexmccabe/pen/LNdBKY

Upvotes: 1

Juan Fernandez Ridano
Juan Fernandez Ridano

Reputation: 31

The best way is if you use .toggle(), then there you only need to put the "new" class, and instead of mousenter() and mouseleave() just use hover().

$( "p" ).hover(function() {

     $( this ).toggleClass("blue");

});

and in your css file:

.blue {

    color: blue;

}

Upvotes: 1

Faizaan Nawaz
Faizaan Nawaz

Reputation: 86

Just save the initial color in a variable and set it on mouse leave.

$(document).ready(function() {
   var InitialColor = $("p").css("color")
   $("p").mouseenter(function() {
       $(this).css("color", "yellow")
   })
    .mouseleave(function() {
      $(this).css("color", InitialColor)
    })
})

https://jsfiddle.net/owzm64wa/

Upvotes: 0

Mike B
Mike B

Reputation: 2784

Use classes. On mouseEnter add class $(this).addClass("the_new_color") and on mouseLeave just remove it. $(this).removeClass("the_new_color"). That css class should have !important to override the initial color.

Upvotes: 2

j08691
j08691

Reputation: 208002

Just set the color to an empty string and it will use the value you initially set:

.mouseleave(function() {
  $(this).css("color", "")
})

jsFiddle example

Upvotes: 2

Related Questions