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.
1 Answer 1
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');
}
});