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 Perfect

Conditional for select and ul menu?

I am working on making a sticky menu that scrolls to a specific div based on what menu item is pressed. I got it to scroll both when the menu is a dropdown and when it is a list based on the window size. My question is whenever I try to place my jQuery into a conditional, the scroll feature does not implement correctly for one of the menu types, why?

<!-----Create Dropdown----> var $select = $("<select></select>"); $("#menu").append($select); $("#menu a").each(function(){ var $anchor = $(this); var $option = $("<option></option>"); $option.val($anchor.attr("href")); $option.text($anchor.text()); $select.append($option); });

<!-----Scroll based on menu item clicked----> ****Putting both into an if else causes only one to work and I have to refresh the screen for the other to scroll correctly) display values are changed in my CSS file using media queries

if($('#ulist').css('display') == 'none'){ //ulist is ul id

$('select').click(function(){ var value = "#" + $(this).find(":selected").text(); value = value.toLowerCase(); $('html,body').animate({scrollTop:$(value).offset().top - $('#menu').height()}, 800);
});

}else{ $('#menu li a').click(function(){ var value =$(this).attr("href");
$('html,body').animate({scrollTop:$(value).offset().top - $('#menu').height()}, 800);
}); }

$('#menu').sticky();

Thanks in advance for any help!

1 Answer

If I getting clear your answer, you should prevent default link action and append action on inserted new values? In your case:

    $('#menu li a').click(function(e) {

        e.preventDefault();

        var value = $(this).attr("href");
        $('html,body').animate({
            scrollTop: $(value).offset().top - $('#menu').height()
        }, 800);
    });

to not make default link click action. Else if you create new DOM element you should use extended jQuery function syntax:

$().on('click', 'elementSelectorYouNeed', function(){}) 

vs.

$().on('click', function(){})