SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: Jquery for loop

  1. #1
    SitePoint Zealot
    Join Date
    Jan 2007
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Jquery for loop

    I was building a site where you roll over a list of links and the class changes and also a box of information changes, my code works like this:

    $(document).ready(function() {
    $("#link1").mouseover(function () {
    for (var i=1; i < 7; i++){

    $("#link"+i).removeClass("orangeArrow");
    $("#link"+i).addClass("greenArrow");
    $("#toggle"+i).css("display","none");
    }
    $("#link1").removeClass("greenArrow");
    $("#link1").addClass("orangeArrow");
    $("#toggle1").css("display","block");
    });
    });

    but i had to rewrite this code for all 6 elements i had imagined it to work like this to cycle through all 6 elements and add the correct listener:

    $(document).ready(function() {
    for (var j=1; j<7; j++){
    $("#link"+j).mouseover(function () {
    for (var i=1; i < 7; i++){

    $("#link"+i).removeClass("orangeArrow");
    $("#link"+i).addClass("greenArrow");
    $("#toggle"+i).css("display","none");
    }
    $("#link"+j).removeClass("greenArrow");
    $("#link"+j).addClass("orangeArrow");
    $("#toggle"+j).css("display","block");
    });
    }
    });

    the result i had was that the listener event was present but it only cycled through the the for i loop, and just ignored the second part.

    As i write this i realise there would be no j variable when it is called? Any ideas on getting this tidier

  2. #2
    Function Curry'er JimmyP's Avatar
    Join Date
    Aug 2007
    Location
    Brighton, UK
    Posts
    2,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would give each link a class of "link" and then possibly something like this:

    Code JavaScript:
    jQuery(document).ready(function(){
    	$('.link').mouseover(function(){
    		$('.link').each(function(i){
    			$(this).removeClass("orangeArrow").addClass("greenArrow");
    			$("#toggle"+i).css("display","none");
    		})
    	})
    });

    Notice the use of the each() function - detailed here: http://docs.jquery.com/Each
    James Padolsey
    末末末末末末末末末末末末末末末末末末末
    Awesome JavaScript Zoomer (demo here)
    'Ajaxy' - Ajax integration solution (demo here)

  3. #3
    SitePoint Zealot
    Join Date
    Jan 2007
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I did try this but it did not seem to work correctly

    I want a list of links to be highlighted as you roll over and the content to display aswell


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •