2
\$\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\$
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\$
  • \$\begingroup\$ Thank you @Shlomi, what about if the same code happen after click not hover \$\endgroup\$ – Déjà Bond Jun 8 '13 at 18:25
  • \$\begingroup\$ @JimmyTodd then u can use replace the hover with toggle \$\endgroup\$ – Shlomi Komemi Jun 9 '13 at 7:34
  • \$\begingroup\$ Note that the .toggle() event binding function was removed in v1.9. \$\endgroup\$ – nnnnnn Jun 13 '13 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 '18 at 22:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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