Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jquery 'this' to condense code

I try not to ask questions, but I can't figure out what should be very easy. I'm building a site for practice briannabaldwinphotography.com. I'm just trying to condense this so that I could just click on an anchor and it smooth scrolls to a <section> with an id the same name as the anchor. Ex: the 'about' li anchor has an href of #section_three and will scroll to the <section> with an id of section_three. I tried like 10 different variations and it won't work for me. Sort of what I'm looking for would be $(this).attr("href").offest().top}....etc. Here is the code I want to condense. Thanks.

$(function() {
    $("[href='#section_three']").on("click", function() {
        $("html body").animate({"scrollTop":$("#section_three").offset().top}, 1000);
        return false;

    });
    $("[href='#section_two']").on("click", function() {
        $("html body").animate({"scrollTop":$("#section_two").offset().top}, 1000);
        return false;


    });
    $("[href='#section_four']").on("click", function() {
        $("html body").animate({"scrollTop":$("#section_four").offset().top}, 1000);
        return false;


    });
    $("[href='#section_one']").on("click", function() {
        $("html body").animate({"scrollTop":$("#section_one").offset().top}, 1000);
        return false;


    });

});
like image 919
Chris Avatar asked Feb 11 '26 18:02

Chris


1 Answers

If you use the attribute starts with selector (^=) you can get all elements with an href beginning with "#section_", bind a handler to those, then within the handler use this.href to get the href of the particular element that was clicked:

$(function() {
    $("[href^='#section_']").on("click", function() {
        $("html body").animate({"scrollTop" : $(this.href).offset().top}, 1000);
        return false;
    });
});

Note that this.href does the same job as $(this).attr("href"), but more efficiently: no need to create a jQuery object to access a property of the element that you can get to directly.

like image 105
nnnnnn Avatar answered Feb 13 '26 08:02

nnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!