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");
        }
    });
});

3
  • 2
    Separate IDs with a comma: $("#client, #portfolio, #features, #get")... Commented Aug 8, 2016 at 10:04
  • Separate the id's using a comma. Eg $("#id1, #id2, #id3").clicl(); Commented Aug 8, 2016 at 10:05
  • You don't need to separate the IDs, as you don't need to know them at all... see my answer for an example. Commented Aug 8, 2016 at 10:23

6 Answers 6

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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) { ...

5 Comments

Whenever it is not dynamically you should use a direct event listener $("[data-scroll-target]").on("click", function(e) { });
@eisbehr what restricts that?
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 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.
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
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.

1 Comment

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(/**/).
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");
    }
  });
});

Comments

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)

Comments

-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>

5 Comments

@eisbehr, fixed it.
@eisbehr - Why use a comma list? Check my answer for a dynamic solution.
@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, 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 that was a reply to evolutionxbox comment. Your answer is fine! ;)

Your Answer

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.