How can i combine this codes?

As the title says, I think this code can be simplified in less lines. Could someone help me with this?

    $('a[href=#over]').click(function(){
    $('html, body').animate({
        scrollTop: $("#over").offset().top - 100
    }, 2000);
});

$('a[href=#diensten]').click(function(){
    $('html, body').animate({
        scrollTop: $("#diensten").offset().top - 100
    }, 2000);
});

$('a[href=#portfolio]').click(function(){
    $('html, body').animate({
        scrollTop: $("#portfolio").offset().top - 100
    }, 2000);
});

$('a[href=#contact]').click(function(){
  $("html, body").animate({ scrollTop: $(document).height() }, 2000);
});

$('a[href=#top]').click(function(){
    $('html, body').animate({scrollTop:0}, 2000);
    return false;
});

I was thinking myself off an if/elseif statement, but im kinda stuck in there. So could you please have an look?

Answers


This wasn't tested. It is just your code that I minified (and optimized a little bit).

$('a[href]').click(function(){
    var href = $(this).attr('href');
    var htmlbody = $('html,body');
    if( href == '#over' || href == '#diensten' || href == '#portfolio' )
    htmlbody.animate({ scrollTop: $(href).offset().top - 100 }, 2000);
    if( href == '#contact' )
    htmlbody.animate({ scrollTop: $(document).height() }, 2000);
    if( href == '#top' )
    htmlbody.animate({ scrollTop: 0 }, 2000);
});

You can use the href attribute of anchors for selecting the element by IDs.

$('a').click(function(){
    var id = this.href;
    $('html, body').animate({
        scrollTop: $(id).offset().top - 100
    }, 2000);
});

$('a').click(function(e) {
    e.preventDefault();
    var id = this.href;
    var scroll = '';
    if (id === '#contact') {
       scroll =  $(document).height();
    } else if (id === '#top') {
       scroll = 0;
    } else {
       scroll = $(id).offset().top - 100;
    }
    $('html, body').animate({
           scrollTop: scroll
    }, 2000)
});

$('a').click(function(){

    var id = $(this).attr("href");

    if(id in {"#over": 1, "#diensten": 1, "#portfolio": 1}) {
      $('html, body').animate({ scrollTop: $(this).offset().top - 100 }, 2000);
    } 
    else if(id === "#contact") {
       $("html, body").animate({ scrollTop: $(document).height() }, 2000);
    } 
    else {
      $('html, body').animate({scrollTop:0}, 2000);
      return false;
    }
});

Need Your Help

google chart dashboard reset

javascript jsf google-visualization

I've got a dashboard with a ChartRangeFilter and a LineChart in my JSF page. before I added the dashboard and filter, my clear chart function using chart.clear() worked fine on the LineChart alone,...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.