1
\$\begingroup\$

I'm a newbie to javascript, and day after day, I try to write better code with jQuery.

For example, I wrote this code earlier:

$$foo= $(".foo");

$$foo.mouseenter(function() {
    $(this).find('h1').addClass("hover");
});

$$foo.mouseleave(function() {
    $("h1").removeClass("hover");
});

What I want to happen with this code is when the mouse enters .foo the h1 gets a new background color or any style applying on class, hover.

Another example:

$$foo= $(".foo");

$$foo.mouseenter(function() {
    $(this).find('h1').addClass("hover");
    $(this).find('input').focus();
});

$$foo.mouseleave(function() {
    $("h1").removeClass("hover");
    $(".foo input").val('');
});

What I want to happen here is when the mouse enters .foo the input gets focus, and when mouse out the input's values are removed.

Both cases are working perfect, but I want to know if there is a better way to do this (mouse enter and mouse out)?

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

First of all you can use jQuery hover and passing 2 functions (mouseenter, mouseleave) and u can shorten it also with jQuery end

$('.foo').hover(
    function () {
        $(this).find('h1').addClass("hover").end().find('input').focus();            
    },
    function () {
        $(this).find('h1').removeClass("hover").end().find('input').val('');            
    }
);
\$\endgroup\$
4
  • \$\begingroup\$ Thank you @Shlomi, what about if the same code happen after click not hover \$\endgroup\$ Jun 8, 2013 at 18:25
  • \$\begingroup\$ @JimmyTodd then u can use replace the hover with toggle \$\endgroup\$ Jun 9, 2013 at 7:34
  • \$\begingroup\$ Note that the .toggle() event binding function was removed in v1.9. \$\endgroup\$
    – nnnnnn
    Jun 13, 2013 at 12:37
  • \$\begingroup\$ @StefanBob - according to the doco the .hover() event binding method is still supported. Do you have a link to doco that says otherwise? \$\endgroup\$
    – nnnnnn
    Apr 9, 2018 at 22:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.