RB Studios RB Studios - 7 months ago 38
Javascript Question

Use jQuery attr to scroll to data?

I was wondering how I would use this method:

$('[data-jump-spy]').each(function(){
var dataObj = .data('jump-spy');
$(this).onclick ({
scrollTop: $("#" + dataObj ).offset().top();
});
});


to attach it to a link like so:

<a href="javascript:void(0);" data-jump-spy="divContentThatsFarDownPage">Who we are</a>
....
....
....
....
<div class="box radius box-grey --animate" id="divContentThatsFarDownPage">
....
</div>



Final Solution can be found below


This function will allow you to code your website more easily. Simply type
<div class="whatever iconArrow-to-Content LinkText-to-Content Img-to-Content" data-jump-spy="page-content"


$('[data-jump-spy]').each(function(){
var dataObj = $(this).data('jump-spy');
$(this).click(function() {
$("html, body").animate({
scrollTop: $("#" + dataObj ).offset().top
}, 1000);
});
});

Answer

A couple of changes

$('[data-jump-spy]').each(function(){
     var dataObj = $(this).data('jump-spy'); // needs $(this) at beginning since .data needs to run on some object
     $(this).click(function(){ // used click instead of onclick and you need to pass a function as an argument
              $('html,body').animate({scrollTop: $("#" + dataObj ).offset().top}); // use .top instead of .top() as it is a property and not a method
     });
});