Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ScrollTO with data attributes

I really need help with this issue, my knowledge with JS is not that good. So, basically I want to scroll to the section when the link is clicked, but not through (href="#target"), I want to do it with attributes. Also, I want to add attribute offset from top as well if it is possible. Please take a look at the code, you will get a clearer picture.

HTML Example:

<nav>
    <a href="#" data-attr-scroll="#section1" class="scrollto">Section 1</a>
    <a href="#" data-attr-scroll="#section2" class="scrollto">Section 2</a>
    <a href="#" data-attr-scroll="#section3" class="scrollto">Section 3</a>
    <a href="#" data-attr-scroll="#section4" class="scrollto">Section 4</a>
    <a href="#" data-attr-scroll="#section5" class="scrollto">Section 5</a>
</nav>

<div class="test" id="section1">
    #1 Section
</div>
<div class="test" id="section2" data-scroll-offset="100">
    #2 Section
</div>
<div class="test" id="section3">
    #3 Section
</div>
<div class="test" id="section4" data-scroll-offset="200">
    #4 Section
</div>
<div class="test" id="section5" data-scroll-offset="300">
    #5 Section
</div>

JS example:

    jQuery(document).ready(function($) {
        $(".scrollto").click(function(event) {
            event.preventDefault(); 

            var defaultAnchorOffset = 0;

            var $anchor = $(this).attr('data-attr-scroll');

            var anchorOffset = $anchor.attr('data-scroll-offset');
            if (!anchorOffset)
                anchorOffset = defaultAnchorOffset; 

            $('html,body').animate({ 
                scrollTop: $anchor.offset().top - anchorOffset
            }, 500);        
        });
    });

CSS example:

    nav {
        position: fixed;
        top: 20px;
        right: 20px;
    }
    .test {
        height: 500px;
    }

I know that JS code is bad. If anyone can help me, I would be very grateful.

Thank you in advance.

Regards, Danny

Fiddle Demo

like image 570
Danny Avatar asked Feb 03 '14 15:02

Danny


1 Answers

here you go, i´d rather take a string representation of the id and concatinate the selector, it works fine !

    jQuery(document).ready(function($) {
    $(".scrollto").click(function(event) {
        event.preventDefault(); 

        var defaultAnchorOffset = 0;

        var anchor = $(this).attr('data-attr-scroll');

        var anchorOffset = $('#'+anchor).attr('data-scroll-offset');
        if (!anchorOffset)
            anchorOffset = defaultAnchorOffset; 

        $('html,body').animate({ 
            scrollTop: $('#'+anchor).offset().top - anchorOffset
        }, 500);        
    });
});

i think it didnt work cause you tryed to cast an object from a string

heres a fiddle, have fun !

http://jsfiddle.net/JcEb3/1/

like image 199
john Smith Avatar answered Oct 10 '22 01:10

john Smith