DeadlyDagger
DeadlyDagger

Reputation: 609

Jquery- .each() doesn't work

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

Answers (5)

m.t.bennett
m.t.bennett

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

Paresh Balar
Paresh Balar

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

Shadow Wizard
Shadow Wizard

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");
});

Live test case. ​

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

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

Rory McCrossan
Rory McCrossan

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") });
});

Example fiddle

Upvotes: 1

Related Questions