0

here is my jquery code i want to work with different ids but same function. now in my coding same function/code is being repeated with every different id , but i want to make a single function for all different ids to reduce the code . how can i do this ?

/$(function(){
//    
//    $('a[href^="#"') .click(function(e){
//        var target = $(this).attr('href');
//        var strip = target.slice(1);
//        var anchor = $ ("a[name='" + strip +"']");
//        e.preventDefault();
//        $('html,body').animate({
//            scrollTop: anchor.offset().top
//        },(3000));
//    });
//});
$("#get").click(function(){
    $('html, body').animate({
        scrollTop: $("#getto").offset().top
    }, 2000);
});

$("#features").click(function() {
    $('html, body').animate({
        scrollTop: $("#featuresto").offset().top
    }, 2000);
});
1
//$("#myElement").offset({left:34,top:100});

$("#portfolio ").click(function() {
    $('html, body').animate({
        scrollTop: $("#portfolioto").offset().top
    }, 2000);
});

$("#client").click(function() {
    $('html, body').animate({
        scrollTop: $("#clientto").offset().top
    }, 2000);
});

$("#work").click(function() {
    $('html, body').animate({
        scrollTop: $("#workto").offset().top
    }, 2000);
});

$("#contact").click(function() {
    $('html, body').animate({
        scrollTop: $("#contactto").offset().top
    }, 2000);
});



jQuery(document).ready(function($) {
    $(window).scroll(function () {
        if ($(window).scrollTop() >= 100) { 
            $(".header").addClass("navbar-fixed-top");  
        }
        else{
           $(".header").removeClass("navbar-fixed-top");
        }
    });
});


    jQuery(document).ready(function($) {
    $(window).scroll(function () {
        if ($(window).scrollTop() >= 200) { 
            $(".gototop").addClass("appare");  
        }
        else{
           $(".gototop").removeClass("appare");
        }
    });
});
coder
  • 25
  • 3

6 Answers6

3

You can combine the selector and use the id to get the scrollTo element.

$("#get, #features, #portfolio, #client, #work, #contact").click(function() {
    $('html, body').animate({
        scrollTop: $("#" + $(this).attr("id") + "to").offset().top
    }, 2000);
});
eisbehr
  • 12,243
  • 7
  • 38
  • 63
3

If you often need this functionality, then you can introduce a class like .scroll-on-click which will enable scroll-on-click behavior and use HTML data attribute for storing its scroll target.
Or you can make it even simpler - just use this attribute for attaching a handler:

$(document).on("click", "[data-scroll-target]", function(e) {
    var target = $(this).attr("data-scroll-target");
    $('html, body').animate({
        scrollTop: $(target).offset().top
    }, 2000);       
});

Then, in your HTML simply use this attribute:

<a href="#" data-scroll-target="#contactto">Go to Contact-to</a>
<a href="#" data-scroll-target="#workto">Go to Work-to</a>
etc.

As @eisbehr mentionted in comment, use event delegation (in example above) if you want to enable this behavior for dynamically generated elements too. Otherwise, you can simply attach it directly in order to slightly improve its performance:

$("[data-scroll-target]").click(function(e) { ...
Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • 1
    Whenever it is not dynamically you should use a direct event listener `$("[data-scroll-target]").on("click", function(e) { });` – eisbehr Aug 08 '16 at 10:08
  • 1
    @eisbehr what restricts that? – Bhojendra Rauniyar Aug 08 '16 at 10:08
  • Think about what a live delegation does on every `click`. Tries to find `[data-scroll-target]` in `document` every time. It can't be as fast as a direct listener. ;) @BhojendraNepal – eisbehr Aug 08 '16 at 10:13
  • @eisbehr event delegation method would be faster than direct listener because direct listener needs search from `html` but event delegation requires to search from its parent in the example `body`. – Bhojendra Rauniyar Aug 08 '16 at 10:15
  • But it only do it once and not on every `click`. And because the delegation is registered on `document` it would be just the same action as did by a direct listener, with the difference that it happens all the time then. See the updated answer above with the linked question here on SO. And you can even create a direct listener within a context, if you already get it somewhere, like `$("a", this).click(function() {});` what is the same as `$(this).on("click", "a", function() {})` @BhojendraNepal – eisbehr Aug 08 '16 at 10:19
1

Simply pass all the id's in single function

/$(function(){
//    
//    $('a[href^="#"') .click(function(e){
//        var target = $(this).attr('href');
//        var strip = target.slice(1);
//        var anchor = $ ("a[name='" + strip +"']");
//        e.preventDefault();
//        $('html,body').animate({
//            scrollTop: anchor.offset().top
//        },(3000));
//    });
//});


$("#get, #features, #portfolio, #client, #work, #contact").click(function() {
  $('html, body').animate({
     scrollTop: $("#" + $(this).attr("id") + "to").offset().top
  }, 2000);
});



jQuery(document).ready(function($) {
    $(window).scroll(function () {
        if ($(window).scrollTop() >= 100) { 
            $(".header").addClass("navbar-fixed-top");  
        }
        else{
           $(".header").removeClass("navbar-fixed-top");
        }
    });
    $(window).scroll(function () {
        if ($(window).scrollTop() >= 200) { 
            $(".gototop").addClass("appare");  
        }
        else{
           $(".gototop").removeClass("appare");
        }
    });
});

Edit : No need to use 2 .ready() function as you can write both the scroll function in one as above.

Gaurav Aggarwal
  • 9,809
  • 6
  • 36
  • 74
  • Just a further hint: when saying there is no need to use two `ready` states, you could even combine the `scroll` listener or chain them, to prevent double cast to jQuery `$(window).scroll(/**/).scroll(/**/)`. – eisbehr Aug 08 '16 at 10:22
0

Separate the id's using a comma. Eg $("#id1, #id2, #id3").click();

Here is the simplified code:

//$(function(){
//
//    $('a[href^="#"') .click(function(e){
//        var target = $(this).attr('href');
//        var strip = target.slice(1);
//        var anchor = $ ("a[name='" + strip +"']");
//        e.preventDefault();
//        $('html,body').animate({
//            scrollTop: anchor.offset().top
//        },(3000));
//    });
//});

$("#get, #features, #portfolio, #client, #work, #contact").click(function() {
  var id = "#" + $(this).attr('id') + "to";
  $('html, body').animate({
    scrollTop: $(id).offset().top
  }, 2000);
});


jQuery(document).ready(function($) {
  $(window).scroll(function() {
    if ($(window).scrollTop() >= 100) {
      $(".header").addClass("navbar-fixed-top");
    } else {
      $(".header").removeClass("navbar-fixed-top");
    }

    if ($(window).scrollTop() >= 200) {
      $(".gototop").addClass("appare");
    } else {
      $(".gototop").removeClass("appare");
    }
  });
});
Pugazh
  • 9,453
  • 5
  • 33
  • 54
0

Your commented out code was very close to what I consider a succinct and simple answer. I dislike the "hardcoding" of IDs in JS as they are likely to change.

I have altered it slightly below (div's are for spacing only):

$('[href^="#"]') .click(function(e){
  var hash = this.hash.substr(1);
  e.preventDefault();
  $('html,body').animate({
    scrollTop: $('[name=' + hash + 'to]').offset().top
  },(3000));
});
div {
  height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#get">Get</a>

<div class="spacer"></div>

<a name="getto">Get to</a>

<div class="spacer"></div>
  • It uses this.hash to get the hash value of the anchor href.
  • The anchor hash value can be dynamic, (avoiding the ID chain in other answers)
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
-2

You can use seperate selectors together by seperating them with comma. Inside the event handler, use this to access the element that the event was fired for.

$("#get,#features,#portfolio,#client,#work,#contact").click(function() {
  $('html, body').animate({
    scrollTop: $("#" + $(this).attr("id") + "to").offset().top
  }, 2000);
});
div {
  margin-top: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="get">Get</button>
<button id="features">Features</button>
<button id="portfolio">Portfolio</button>
<button id="client">Client</button>
<button id="work">Work</button>
<button id="contact">Contact</button>


<div id="getto">Get</div>
<div id="featuresto">Features</div>
<div id="portfolioto">Portfolio</div>
<div id="clientto">Client</div>
<div id="workto">Work</div>
<div id="contactto">Contact</div>
Ozan
  • 3,709
  • 2
  • 18
  • 23
  • @eisbehr, fixed it. – Ozan Aug 08 '16 at 10:14
  • @eisbehr - Why use a comma list? Check my answer for a dynamic solution. – evolutionxbox Aug 08 '16 at 11:07
  • @evolutionxbox This is not my answer. But as you ask me: your answer is really good in my eyes, because you assume that he uses only `a` tags. And did your own things. This is not wrong, but not a good answer to a question, because of this it is possible not working for the creator. Like seeing here with buttons and divs ... :) – eisbehr Aug 08 '16 at 11:12
  • @eisbehr, buttons and divs are irrelevant in the example. The example is using the id values OP gave in his question. You could replace them with any other element and the example would still work. – Ozan Aug 08 '16 at 11:17
  • @Ozan that was a reply to evolutionxbox comment. Your answer is fine! ;) – eisbehr Aug 08 '16 at 11:20