I have a navigation function I've created to scroll my webpage horizontally, this works fine however I'm guessing it could be written much better. Can anybody give me advice on what I could be doing logic wise to minimise my code?
jQuery
$('.sectionOne').click(function(e){
e.preventDefault();
$('nav').find('.active').removeClass('active');
$(this).addClass('active');
$('.scene').animate({
'marginLeft' : -$('.section-one').offset().left
});
});
$('.sectionTwo').click(function(e){
e.preventDefault();
$('nav').find('.active').removeClass('active');
$(this).addClass('active');
$('.scene').animate({
'marginLeft' : -$('.section-two').offset().left
});
});
$('.sectionThree').click(function(e){
e.preventDefault();
$('nav').find('.active').removeClass('active');
$(this).addClass('active');
$('.scene').animate({
'marginLeft' :-$('.section-three').offset().left
});
});
$('.sectionFour').click(function(e){
e.preventDefault();
$('nav').find('.active').removeClass('active');
$(this).addClass('active');
$('.scene').animate({
'marginLeft' : -$('.section-four').offset().left
});
});
$('.sectionFive').click(function(e){
e.preventDefault();
$('nav').find('.active').removeClass('active');
$(this).addClass('active');
$('.scene').animate({
'marginLeft' : -$('.section-five').offset().left
});
});
$('.sectionSix').click(function(e){
e.preventDefault();
$('nav').find('.active').removeClass('active');
$(this).addClass('active');
$('.scene').animate({
'marginLeft' : -$('.section-six').offset().left
});
});
$('.sectionSeven').click(function(e){
e.preventDefault();
$('nav').find('.active').removeClass('active');
$(this).addClass('active');
$('.scene').animate({
'marginLeft' : -$('.section-seven').offset().left
});
});
HTML
<!-- Navigation -->
<nav>
<ol>
<li><a href="#" data-section="section-one" class="active sectionOne">1</a></li>
<li><a href="#" data-section="section-two" class="sectionTwo">2</a></li>
<li><a href="#" data-section="section-three" class="sectionThree">3</a></li>
<li><a href="#" data-section="section-four" class="sectionFour">4</a></li>
<li><a href="#" data-section="section-five" class="sectionFive">5</a></li>
<li><a href="#" data-section="section-six" class="sectionSix">6</a></li>
<li><a href="#" data-section="section-seven" class="sectionSeven">7</a></li>
</ol>
</nav>
It looks very redundant. How about something like:
$('nav a').click(function(e){
e.preventDefault();
$('nav a.active').removeClass('active');
$(this).addClass('active');
$('.scene').animate({
'marginLeft' : -$('.' + $(this).attr('data-section')).offset().left
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.