Creating variables for selectors


#1


https://www.codecademy.com/en/courses/jquery-ext/projects/jquery-prj_madison-square-market?user_id=57df7f85e92d416a3f000679


Hi all, I came across a more efficient way to toggle the onclick dropdown menu and hide the others.

// create a variable for the onclick menu
var thisMenu = $(this).find('.dropdown-menu');
if ($(thisMenu).css('display') === 'none') {
    $('.dropdown-menu').hide();
}
$(thisMenu).toggle();


Just a quick question. Is it more conventional to store the variable as following or the way I did it?

var $thisMenu = $($(this).find('.dropdown-menu'));

#2

Hey @bitrockstar88319,

I think that either method you used for the variable is fine, but I'm not a JavaScript expert. I do think there's an easier way to do it though, since jQuery is designed to make things like this very easy. This is the code I have inside my main function:

$('.dropdown').click(function() {
  $(this).find('.dropdown-menu').fadeToggle();
});

I hope this helps a little :slight_smile:


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.