-1
$(document).ready(function()
{
    $for(i=1;i<8;i++)
    {
        $("#"+i).hover(function() {
             $("#"+i).stop().animate({left:"50px"});
        },
        function() {
             $("#"+i).stop().animate({left:"30px"});
        });
    } 
 });

I used for loop here to avoid multiple declaration of hover function it doesnt work how can i declare my div id my div id was 1-7.plz tell me how i should use the div ids inside the loop.

Adam Rackis
  • 79,454
  • 49
  • 255
  • 377

5 Answers5

4

It looks like you are using numbers as ids, here is a great answer on StackOverflow that describes how to create IDs: What are valid values for the id attribute in HTML?.

$(document).ready(function()
{
    for(var i = 1; i < 8; i++)//see that I removed the $ preceeding the `for` keyword, it should not have been there
    {
        $("#"+i).hover(function() {
             $(this).stop().animate({left:"50px"});//also notice that instead of using `"#" + i` as the selector inside the anonymous function I changed it to `this` so it properly references the hovered element
        },
        function() {
             $(this).stop().animate({left:"30px"});
        });
    } 
});

If you add a class to all of the elements you are binding to this can be majorly simplified:

$(function()
{
    $(".hover-class").hover(function() {
         $(this).stop().animate({left:"50px"});
    },
    function() {
         $(this).stop().animate({left:"30px"});
    });
});

Here is a demo of this solution: http://jsfiddle.net/FJQNa/

This will select all the elements with the hover-class class and bind the mouseover/mouseout event handlers to them.

EDIT

You can also select multiple elements at once using ids by separating selectors with commas:

$(function()
{
    $("#ele-1, #ele-2, #ele-3, #ele-4, #ele-5, #ele-6, #ele-7").hover(function() {
         $(this).stop().animate({left:"50px"});
    },
    function() {
         $(this).stop().animate({left:"30px"});
    });
});

Docs for multiple selectors in jQuery: http://api.jquery.com/multiple-selector/

Community
  • 1
  • 1
Jasper
  • 74,169
  • 13
  • 144
  • 142
  • thank you can u tell me how can i declare it . to avoid its multiple declaration – PremStephenIrudayaraj Dec 15 '11 at 18:21
  • @user1100418 I'm not sure I understand your question. If you are talking about the second code example in my answer, then check-out the jsfiddle (the link below the code) and you can see how the HTML/CSS/JS are implemented. – Jasper Dec 15 '11 at 18:25
3

This is how you make a for loop in JavaScript:

for(var i = 1; i < 8; i++)

No jQuery needed.

Also, you're using numbers as ids for your dom elements, which is invalid. IDs are supposed to start with a letter.

Also, those inner functions are using your loop's variable, which is not going to work; you'll wind up with each handler trying to select element 8 since each handler is closing over i.

To pass the current value of a changing loop variable to an underlying event handler, you'd have to "break the closure" like this:

$("#el"+i).hover(
    (function(local_i) { return function() {  $("#el"+ local_i).stop().animate({left:"50px"});  } })(i),
    (function(local_i) { return function() { $("#el" + local_i).stop().animate({left:"30px"}); } })(i) 
});

But you're really just grabbing the thing you're hovering over, so:

    $("#"+i).hover(function() {
         $(this).stop().animate({left:"50px"});
    },
    function() {
         $(this).stop().animate({left:"30px"});
    });

Should work fine

Adam Rackis
  • 79,454
  • 49
  • 255
  • 377
  • 1
    Plus the fact that scoping is an issue here. But that might go a bit too far if the OP does not know how to make a for loop... – pimvdb Dec 15 '11 at 18:11
  • 1
    Another note: The animation will always run on element with "id" 7, because of i changes at every iteration, and `i` is not captured in a closure. – Rob W Dec 15 '11 at 18:12
  • @pimvdb - oh my - he's using the loop value in events - that won't work at all – Adam Rackis Dec 15 '11 at 18:12
  • 1
    The immediately-invoked anonymous function is definitely overkill here. Also, numeric ids are valid HTML5. – Dennis Dec 15 '11 at 18:20
  • @Dennis - I didn't know numeric id's were valid for html5. Will they break older browsers? – Adam Rackis Dec 15 '11 at 18:22
  • @AdamRackis http://jsfiddle.net/QHevQ/ They work fine in IE7, I've never had problems with numeric ids (not that I use them that often). – Dennis Dec 15 '11 at 18:25
  • @Dennis - it's always interesting to see what invalid things older browsers will tolerate. Thanks. – Adam Rackis Dec 15 '11 at 18:29
  • 1
    @user1100418 - great, glad to hear it. And welcome to Stack Overflow. Make sure you mark whichever of these answers was most helpful by clicking the check mark next to it. – Adam Rackis Dec 15 '11 at 18:34
3

Use this instead of i. i lasts beyond the for loop so it will always try to access $('#8')`.

$(document).ready(function()
{
    for(var i=1; i<8; i++) //Declare var here otherwise it becomes global and that's not what you want for a simple counter
    {
        $("#"+i).hover(function() { //i is valid here because it gets used synchronously with the loop
             $(this).stop().animate({left:"50px"});
             //Use this instead of i because of "closure."
             //The anonymous function gain access to the variable to be
             // used later, but the loop will continue to increment,
             // changing the value.
        },
        function() {
             $(this).stop().animate({left:"30px"});
        });
    } 
});
Dennis
  • 30,518
  • 9
  • 59
  • 75
0

Classes would be the better solution (another already posed this solution) If you absolutely must use IDs this might work out a little better:

var selector = "#1";
for(var i = 2; i < 8; i++)
   selector+=",#"+i;

$(selector).hover(
function() {
   $(this).stop().animate({left:"50px"});
},
function() {
   $(this).stop().animate({left:"30px"});
});
aepheus
  • 6,747
  • 7
  • 32
  • 50
0

Using classes can not only group them semantically, but also makes selecting them easier. Use this. You can also use jQuery.each() to add behavior to all the selected elements.

$(function () {
    function move50 () {
        $(this).stop().animate({left: "50px"}, 500);
    }
    function move30 () {
         $(this).stop().animate({left: "30px"}, 500);
    }
    $(".mydiv").each(function (i, elem) {
        $(elem).hover(move50, move30);
    });
});

Try it here - http://jsfiddle.net/dkBY2/

dheerosaur
  • 12,775
  • 6
  • 28
  • 30