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 jQuery Basics (2014) Creating a Mobile Drop Down Menu Perform: Part 1

Brendan Moran
Brendan Moran
14,052 Points

jQuery is brilliant! :D

I stopped the video at 4:28 before Andrew launched into his explanation of how to do it. I did what he has exemplified already: went to the API and figured out the appropriate methods. I found the process to be logical and rewarding. I am finding that I am getting the hang of this and Andrew's teaching style is really helping me to take an independent approach. Ok, I guess I've got to fit a question in here somewhere. Does defining the $anchor variable have any benefits for speed or scalability? I didn't declare an $anchor variable, but I can see why he did that. Here's my code:

//Create select box and append to #menu
var $select = $("<select></select>");
$("#menu").append($select);

//Cycle over menu links
$("#menu a").each(function() {
  //Create an option
  var $option = $("<option></option>");
  //Option's value is the href of the link
  var href = $(this).attr("href");
  $option.val(href);
  //Option's text is the text of the link
  var linkText = $(this).text();
  $option.text(linkText);
  //Append option to select
  $select.append($option);
});

2 Answers

rydavim
rydavim
18,813 Points

jQuery is indeed brilliant. I too found this course very rewarding. It's intuitive to use, and a lot of fun to write. :)

On to your question! Hopefully someone will correct me if I'm wrong, but I believe there is a small performance gain to using the $anchor variable. Because you're using $(this) more than once, defining a variable will stop you from having to query for it multiple times.

Happy coding!

Brendan Moran
Brendan Moran
14,052 Points

Great tip, thank you! So what I gather then is that querying with $() is maybe a bit more "work" for the program to do than just calling a variable. Good to know!

Hani Shawa
Hani Shawa
10,008 Points

Am working my way through this course again, and shared this on another post earlier. These two links provide a bit more to backup rydavim's point — on the benefits of caching jQuery selectors.

Selector Caching in jQuery

Why cache jQuery objects?

Brendan Moran
Brendan Moran
14,052 Points

Thank you! Bookmarking this. Love that blog post.