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

JavaScript / jQuery, what would be the best option here ??

Hi everyone!

Below are to snippets of code ive been using, one I found and edited from codepen the other ier just finished learning on treehouse.

Treehouse code seems a lot but feels more problemproof,

Codepen code is really simple and very affective,

I just want peoples opinions on what would be the best practice here?

TreeHouse Code:

//Problem: Menu looks bad on smaller browser widths and then on smaller devices.

//Solution: To hide the text links and swap them out with a more appropriate navigation.

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

//Cycle over menu links
$("#menu a").each(function(){
  var $anchor = $(this);
  //Create an option
  var $option = $("<option></option>");

  //Deal with selected options depending on current page
  if($anchor.parent().hasClass("selected")){
     $option.prop("selected", true);
     }
  //Options value is the href
  $option.val($anchor.attr("href"));
  //Options text is the text of link
  $option.text($anchor.text());
  //Append option to selecet
  $select.append($option);

});

//Bind a change lister to the select
$select.change(function(){
  //Go to the selects location
  window.location = $select.val();
});

CodePen Code: (needs a little more css like display none and block but gives the same result as above with a cool slide transition)

$(document).ready(function() {
    $(".mobile-heading").on('click', function(){
        $(".main-menu").slideToggle("fast");
    });
});

Any advice is welcome! Craig

1 Answer

Sean T. Unwin
Sean T. Unwin
28,690 Points

This is fairly subjective. You would have to make the decision based on several factors such as time, ability, how much you like to code, how much you really want to understand how something works. You may also think about if jQuery is really worth it. It is a sizable library (though popular and could be cached by your users) so if you're only using it for a few tasks and are concerned about premium optimization, with regards to page load, perhaps pure JS is the way to go. However, if you are using jQuery throughout the page to aid with numerous tasks then obviously it will cut down on the amount you personally have to code.

It's all preference vs time vs inquisitiveness. :)