Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Sonny Österlund
Sonny Österlund
6,578 Points

how to loop trough a array inside an object in JQuery

I would like to get some help in a problem I hit when I want to DRY

I want to toggle a <p> to be shown or be hidden when I hit a <a> I have about 15 of them that needs to be shown or hidden at the time a visitor want to read the text. I got it to work for a single object and can copy it and got the whole page to work as it should. However now I would like to loop the code and get every link and every text field where it should be. this is what I have so far but I got stuck dont know where to turn is there anyone out there that might help me?

this is how it looked in original without the loop:

$( "#designhemsidalink" ).click(function( event ){
    "use strict";
    event.preventDefault();
    $( "#designhemsida" ).toggle( "slow" );

    });

And this is the loop I trying right now:

var services = {
            lank: ['#designhemsidalink', '#designwebbutiklink'],
            text: ['#designhemsida', '#designwebbutik']

    };
    $.each(services, function(){
$( this.lank ).click(function( event ){

    event.preventDefault();
    $( this.text ).toggle( "slow" );

    });
    });

Any input would be helpfull

Sonny

1 Answer

Samuel Webb
Samuel Webb
25,370 Points

What about something like this:

var services = {
            lank: ['#designhemsidalink', '#designwebbutiklink'],
            text: ['#designhemsida', '#designwebbutik']
};

for ( var i = 0; i < services.lank.length; i++ ) {
    $( services.lank[i] ).click(function( event ){
        event.preventDefault();
        $( services.text[i] ).toggle( 'slow' );
    });
}
Sonny Österlund
Sonny Österlund
6,578 Points

Hi thank you for your answer however Dreamweaver tells me Don't make functions within a loop

Sonny

Samuel Webb
Samuel Webb
25,370 Points

Yes you shouldn't make functions inside of loops because it then has to create the function over and over again which is inefficient. It's much better to create the function outside of the loop and then use it within the loop. The code I wrote isn't the most efficient, it just gets the job done. There's much room for improvement, but I'll leave it to you to refactor it.