2
\$\begingroup\$

I have a navigation bar without a tags:

 $('div.nav ul li').on('click', function() {
 if($(this).is(':first-child')) {
 $("html, body").animate({
 scrollTop: "0"
 }, 'slow');
 } else if($(this).is(':nth-child(2)')) {
 $("html, body").animate({
 scrollTop: "0"
 }, 'slow');
 } else if($(this).is(':nth-child(3)')) {
 var offset = $('div.features').offset().top;
 $("html, body").animate({
 scrollTop: offset+ 'px'
 }, 'slow');
 } else if($(this).is(':nth-child(4)')) {
 var offset = $(document).height();
 $("html, body").animate({
 scrollTop: offset+ 'px'
 }, 'slow');
 }
 });

I wondered if this way is the best way of doing this. first-child & nth-child(2) goes to the same place, then each child after that - up to 4 has a different position to go to.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 25, 2014 at 11:37
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Yes,

you could for starters derive the child position once with

var index = $('div.nav ul li').index( this )

Then you could adapt to index 0 and 1 in 1 if statement Finally, you could just derive the index and have the animate statement only once.

Something like this in the end might do:

$('div.nav ul li').on('click', function() {
 var index = $('div.nav ul li').index( this ), top;
 if( index < 2 ){
 top = '0';
 }
 if( index == 2 ){
 top = $('div.features').offset().top + 'px'; 
 }
 if( index == 3 ){
 top = $(document).height() + 'px'; 
 }
 if(top){
 $("html, body").animate({
 scrollTop: "0"
 }, 'slow');
 }
});
answered Aug 25, 2014 at 12:42
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.