4
$(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.

7
  • 3
    Please format your question and code so that other people can read it. Commented Dec 15, 2011 at 18:08
  • 1
    This can be done with CSS. No need for jQuery... Commented Dec 15, 2011 at 18:11
  • 1) Do u use numeric ID? 2) for tag has $ - should be an error.
    – Anthony
    Commented Dec 15, 2011 at 18:11
  • 1
    The for keyword doesn't have a $. Commented Dec 15, 2011 at 18:12
  • 2
    Please do not format coding mistakes out of your question as errors are pointed out - it makes the answers look wrong Commented Dec 15, 2011 at 18:26

5 Answers 5

10

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/

2
  • thank you can u tell me how can i declare it . to avoid its multiple declaration Commented Dec 15, 2011 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
    Commented Dec 15, 2011 at 18:25
5

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"});
        });
    } 
});
1
  • thank you can u tell me how can i declare it . to avoid its multiple declaration Commented Dec 15, 2011 at 18:22
4

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

8
  • 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
    Commented Dec 15, 2011 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
    Commented Dec 15, 2011 at 18:12
  • @pimvdb - oh my - he's using the loop value in events - that won't work at all Commented Dec 15, 2011 at 18:12
  • 1
    The immediately-invoked anonymous function is definitely overkill here. Also, numeric ids are valid HTML5.
    – Dennis
    Commented Dec 15, 2011 at 18:20
  • 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. Commented Dec 15, 2011 at 18:34
1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.