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

Simple jQuery Question to Eliminate DRY from my Code

Hey guys,

So I have finally got the confidence to start using jQuery and JavaScript without having to refer to and from Google thanks to Andrew Chalkley.

I have written my first couple of lines to do some animations to some text on my homepage of my site. The problem I'm having is the code seems to DRY a fair bit and I would like to know how to simplify my code.

Here's what I have:

<p class="lead txt-teal" id="txtAnimateLead">Lorem Ipsum Dolor!</p>

<p id="txtAnimateText">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.</p>
$("#txtAnimateLead").hide();
$("#txtAnimateLead").slideUp(300).fadeIn(1800);

$("#txtAnimateText").hide();
$("#txtAnimateText").slideUp(300).fadeIn(1800);

The problem I am having is when I go and declare the ID of txtAnimateText to the paragraph lead and then again to the paragraph which has the ID of txtAnimateText only the lead paragraph is animated and nothing else, this prompted me to then go and write the txtAnimateLead.

What my question is, how can I make the above code be declared to one single ID. I will refer back to the documentation over at jQuery and I'll post my finding up if I find anything.

I hope I'm making sense.

Thanks in advance

Stu : )

2 Answers

Are you trying to assign multiple elements the same id? An id should be unique and only assigned to one element.

If you want to apply the same behavior to both elements, you could give them the same class and have your jQuery use that class as the selector.

Hey Kyle,

of course that makes perfect sense! Thanks for that I always forget that ID's can only be assigned to one element.

Cheers for that!