Reputation: 609
I have these buttons in my form that i want to bind 'mouseenter' and 'mouseleave' events to them this is the code that i wrote
$("button").each(function() {
$(this).bind("mouseenter", function() { $(this).css("border", "1px gray outset") });
$(this).bind("mouseleave", function() { $(this).css("border", "none") });
});
this code only works on the first button and nothing happens to the rest. this is my full code:
$("button").each(function() {
$(this).hover(function() { $(this).css("border", "1px gray outset") }, function() { $(this).css("border", "none") });
$(this).bind("mousedown",$(this).css( "border", "inset"));
$(this).click(DoSubmit($(this), 'CLICK', ''));
});
Upvotes: 0
Views: 1148
Reputation: 1320
Your probably wanting this
$("button").each(function(index,value) {
$(value).bind("mouseenter", function() { $(value).css("border", "1px gray outset"); });
$(value).bind("mouseleave", function() { $(value).css("border", "none"); });
});
Upvotes: 1
Reputation: 338
Write directly :
$("button").mouseenter(function(){ $(this).css("border", "1px gray outset");}).mouseleave(function(){ $(this).css("border", "none");});
JS Fiddle Demo : http://jsfiddle.net/tkSdW/
Upvotes: 2
Reputation: 66389
While your original code is working just fine as it is, I would recommend using the .hover()
method which is doing exactly the same thing but with less code:
$("button").hover(function() {
$(this).css("border", "1px gray outset");
}, function() {
$(this).css("border", "none");
});
Upvotes: 1
Reputation: 195982
Nothing wrong with your code
providing that it is run after the DOM has loaded, that means inside
$(function(){
$('button')...
});
Additionally, you do not have to use each, if you are only using the iterations to bind events to the current element..
You can bind directly to a whole group with
$("button")
.bind("mouseenter", function() { $(this).css("border", "1px gray outset") })
.bind("mouseleave", function() { $(this).css("border", "none") });
Upvotes: 2
Reputation: 337560
There is no need to assign event handler in an each()
loop. The selector alone will return an array of elements, and jQuery will then apply the event to those elements:
$(function() {
$("button").bind("mouseenter", function() { $(this).css("border", "1px gray outset") });
$("button").bind("mouseleave", function() { $(this).css("border", "none") });
});
Upvotes: 1