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)?
1 Answer 1
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('');
}
);
-
\$\begingroup\$ Thank you @Shlomi, what about if the same code happen after click not hover \$\endgroup\$Déjà Bond– Déjà Bond2013年06月08日 18:25:27 +00:00Commented Jun 8, 2013 at 18:25
-
\$\begingroup\$ @JimmyTodd then u can use replace the hover with toggle \$\endgroup\$Shlomi Komemi– Shlomi Komemi2013年06月09日 07:34:45 +00:00Commented Jun 9, 2013 at 7:34
-
\$\begingroup\$ Note that the
.toggle()
event binding function was removed in v1.9. \$\endgroup\$nnnnnn– nnnnnn2013年06月13日 12:37:51 +00:00Commented 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– nnnnnn2018年04月09日 22:33:40 +00:00Commented Apr 9, 2018 at 22:33
Explore related questions
See similar questions with these tags.