Giter VIP home page Giter VIP logo

jquery.scrollto's Introduction

jQuery.scrollTo

Lightweight, cross-browser and highly customizable animated scrolling with jQuery

GitHub version

Installation

The plugin requires jQuery 1.8 or higher.

Via bower:

bower install jquery.scrollTo

Via npm:

npm install jquery.scrollto

Via packagist:

php composer.phar require --prefer-dist flesler/jquery.scrollto "*"

Using a public CDN

CDN provided by jsdelivr

<script src="https://cdn.jsdelivr.net/npm/[email protected]/jquery.scrollTo.min.js"></script>

CDN provided by cdnjs

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/2.1.3/jquery.scrollTo.min.js"></script>

Downloading Manually

If you want the latest stable version, get the latest release from the releases page.

2.0

Version 2.0 has been recently released. It is mostly backwards compatible, if you have any issue first check this link. If your problem is not solved then go ahead and report the issue.

Usage

jQuery.scrollTo's signature is designed to resemble $().animate().

$(element).scrollTo(target[,duration][,settings]);

element

This must be a scrollable element, to scroll the whole window use $(window).

target

This defines the position to where element must be scrolled. The plugin supports all these formats:

  • A number with a fixed position: 250
  • A string with a fixed position with px: "250px"
  • A string with a percentage (of container's size): "50%"
  • A string with a relative step: "+=50px"
  • An object with left and top containining any of the aforementioned: {left:250, top:"50px"}
  • The string "max" to scroll to the end.
  • A string selector that will be relative to the element to scroll: ".section:eq(2)"
  • A DOM element, probably a child of the element to scroll: document.getElementById("top")
  • A jQuery object with a DOM element: $("#top")

settings

The duration parameter is a shortcut to the setting with the same name. These are the supported settings:

  • axis: The axes to animate: xy (default), x, y, yx
  • interrupt: If true will cancel the animation if the user scrolls. Default is false
  • limit: If true the plugin will not scroll beyond the container's size. Default is true
  • margin: If true, subtracts the margin and border of the target element. Default is false
  • offset: Added to the final position, can be a number or an object with left and top
  • over: Adds a % of the target dimensions: {left:0.5, top:0.5}
  • queue: If true will scroll one axis and then the other. Default is false
  • onAfter(target, settings): A callback triggered when the animation ends (jQuery's complete())
  • onAfterFirst(target, settings): A callback triggered after the first axis scrolls when queueing

You can add any setting supported by $().animate() as well:

  • duration: Duration of the animation, default is 0 which makes it instantaneous
  • easing: Name of an easing equation, you must register the easing function: swing
  • fail(): A callback triggered when the animation is stopped (f.e via interrupt)
  • step(): A callback triggered for every animated property on every frame
  • progress(): A callback triggered on every frame
  • And more, check jQuery's documentation

window shorthand

You can use $.scrollTo(...) as a shorthand for $(window).scrollTo(...).

Changing the default settings

As with most plugins, the default settings are exposed so they can be changed.

$.extend($.scrollTo.defaults, {
  axis: 'y',
  duration: 800
});

Stopping the animation

jQuery.scrollTo ends up creating ordinary animations which can be stopped by calling $().stop() or $().finish() on the same element you called $().scrollTo(), including the window. Remember you can pass a fail() callback to be called when the animation is stopped.

onAfter and requestAnimationFrame

jQuery.scrollTo has a onAfter callback for work that runs after the animation finishes. It will be called before the scroll event fires. To combat this you can use requestAnimationFrame to do work on the next tick. It is available in many browsers, but you may want to polyfill for the few it does not support.

$.scrollTo(100, {
  onAfter: function() {
    requestAnimationFrame(function() {
        $(".result").addClass("selected");
    });
  }
});

Demo

Check the demo to see every option in action.

Complementary plugins

There are two plugins, also created by me that depend on jQuery.scrollTo and aim to simplify certain use cases.

This plugin makes it very easy to implement anchor navigation. If you don't want to include another plugin, you can try using something like this minimalistic gist.

This plugin simplifies the creation of scrolling slideshows.

Troubleshooting

  • Cannot read property 'propHooks' of undefined: You are most likely using the slim version jQuery, which doesn't include the effects module. The plugin cannot function without it and you'll need the full version.

  • The element doesn't scroll: A good approach to debug is to set overflow: auto temporarily to the scrollable element, to make sure it would be manually scrollable. If you don't see any scrollbar, the problem is likely in the HTML/CSS.

License

(The MIT License)

Copyright (c) 2007 Ariel Flesler [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

jquery.scrollto's People

Contributors

adjohn avatar buzzedword avatar durango avatar flesler avatar igusev avatar jdufresne avatar jeffreyatw avatar jeromev avatar joscha avatar kkirsche avatar lukasdrgon avatar rabadash8820 avatar szepeviktor avatar tmm1 avatar vinnymac avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery.scrollto's Issues

Allowing offset to defined as a function

I have a horizontal list of items in which I need to center the current item. The container that holds the list of items can be easily resized by the user. Therefore, I need the offset setting to be dynamic instead of static.

For this reason, I made the following changes in jquery.scrollTo.js:

  1. At line https://github.com/flesler/jquery.scrollTo/blob/master/jquery.scrollTo.js#L193, I added a function to return the offset value

    function offset() {
    return both($.isFunction(settings.offset) ? settings.offset() : settings.offset);
    }
    
  2. I removed line https://github.com/flesler/jquery.scrollTo/blob/master/jquery.scrollTo.js#L111

  3. I changed line https://github.com/flesler/jquery.scrollTo/blob/master/jquery.scrollTo.js#L157 to

    attr[key] += offset()[pos] || 0;
    

Best regards

What about CSS3 transitions?

Would be great to make use of margin and other hacks in order to make use of css3 hardware accelerated transforms instead of jQuery animate

No minified versions?

Just out of curiosity, why aren't you providing minified versions of these plugins on Github?

New positions not calculated

If a dom element, is changed above the current element, the current element's old position is used, and a new is not calculated in it's place, causing scrolling to be ineffective.

Issue on Safari and Chrome

Hi guys,

I've a issue with the plugin...

This code doesn't work on Safari and Chrome:

$(window).scrollTo('#div', 1000, { queue: true });

It works fine in other browsers like Mozilla and IE.
Any ideia? Thanks

offset broken on dom update

When scrolling to an element and using offset it appears the calculation is made based on the first view of the dom. Any changes to the dom and the offset behaves incorrectly.

For responsive designs, offset needs the ability to be a function [enhancement]

I've tweaked a local copy to allow for offset (and also over) to also accept a function as a value, besides a numeric value or object.

In my case I have a static fixed-top nav bar that may get taller on smaller screens.

I have added one line to the "both" function. Works great. Would be nice to see this in a future release.

function both( val ){
    // test value to see if it is a function
    val = typeof val == 'function' ? val() : val;
    // then run the original test below:
    return typeof val == 'object' ? val : { top:val, left:val };
};

. . .

Here is an example where I am using a dynamic top offset to handle a variable height fixed -position nav bar:

// calculate the offset required based on the navigation bar's current height
var offset = function() {
    return { top: 1 - $('#navtop').height() };
};

// adding scrollTo for navigation anchors
$('#navtop,#navbottom').localScroll({
    hash: false,
    offset: offset,
    easing:'swing',
    duration: 600
});

Its just not working...

ok, so I'm a bit new to jquery and found your plugin totally awesome! but I cannot get it to work, I've been through all the topics posted in issues and the documentation and tried literally all the suggestions made to other but still cannot get it to work. Help please?

The mark up:

Welcome to My company this is the company where you will be in a company

We focus on being the top company of compies especially when companies are likea real company.

More so we also provide companies with things that companies need, like people to be in the company.

the js

jQuery(document).ready(function($) {

$('#nav').localScroll({
    target:'#content_wrap', // Could be a selector or a jQuery object too.
    axis:'x',
    queue:true,
    duration:1500
});

});

Scrolling 2 axes on iPad

I am using scrollTo 1.4.3.1 in combination with localScroll 1.2.8b, jqueryMobile 1.8.0.

localScroll is initiated like this:
$.localScroll({
duration: 1000,
queue:false, //false is diagonal scroll, true is one axis at a time
axis: 'xy'
});

and thereby using links throughout the page in the following way:
home
link2

on desktop everything works fine, but on iPad it only scrolls 1 axis. When setting queue: true, this is very clear....it moves along the x axis, but when going to y it also goes back to the first column.

Any ideas?

Tag 1.4.6 for Twitter Bower

… so that a bower install jquery.scrollTo will install the current 1.4.6 (and not 1.4.5).
Thanks in advance!

Flickering during scroll

New issue with flickering during scroll on Mobile Devices.

After doing some googling and research I see some have solved this problem by adding return false on the click or explicitly setting the axis in the options. Can you look into this? I can provide video if you need. I am using localscroll with hash: false
#33

Chrome 25 broke this?

Hey, had this + localScroll rolling for a while on a website; Chrome 25 seems to have broken it.

All other browsers seem to be working fine, can anyone else confirm this?

Don't work if "wrap" height is 100%

In the demo, if i want the "wrap" be with the same height of browser window to have a "responsive" page, i need to set the wrap height to 100%.

I'm speaking about using your script in a "vertical sliding" situation.

When i do this, the script don't work and i cannot click to next/prev buttons.

My need is to have a "post" with a max dimensions of 800x600 and that reduce size when i go to reduce the windows (wrap) size.

Can you help me?

scrollTo doesn't work on jQuery 1.8 & jQuery UI 1.8.23

I have pinpointed a bug after a few hours of going through my code base and it appears that an upgrade to jQuery 1.8 and jQuery UI 1.8.23 breaks scrollTo(). The last known working version is jQuery 1.7.2 (I haven't tested it on jQuery 1.7.3 yet).

I'm using the following scrollTo command:

$.scrollTo($("[name=page-2]"), {duration: 500, easing: 'swing'})

Have to wait the length of the scroll again

if($.browser.webkit) bodyelem = $("body")
else bodyelem = $("html,body")

$('.autoscroll').click(function() {
$(bodyelem).scrollTo(bodyelem.height(), 10000);
});

I am using this code to scroll to the bottom of the page. I have to wait the scroll time again after the scrolling has finished before being able to scroll again. So a total of 20s in this case.

This is on the latest FF version (16.0.2)

support of jQuery 1.9.x

As I used the jQuery Migrate plug-in to identify code issues in migrating to jQuery 1.9, it showed scrollTo1.4.2 each time I use it (in large Accordion sections to get them to 'top up'). Also, I commented out the script tag linking scrollTo to the page, and ran the page on just jQuery1.9.1 (no Migrate plug-in) and the page loaded, ran fine, and had no errors in the Console.log, other than scrollTo is not a function (anymore). Seems clear that scrollTo1.4.2 uses some deprecated code that is now gone. I don't see any release notes describing a scrollTo version that supports jQuery1.9.x. Seems like a new scrollTo release to support jQuery1.9 is necessary.

I can provide console.log info from the Migrate plug-in, if you need it. Contact me at mlaird (at) alum (dot) mit (dot) edu

Flicker in Firefox ,IE8 and Ipad[IOS 5,6]

Hey I implement ScrollTo in my page but it flicker always as I also fixed the position of that div in which I align all item so when I click on any link the pages goes up and then comes down but it works fine in Chrome.If I add return false then It work same for all browser as it goes up and then comes down.As it has same behavior with when I add return false but it the scoll behavior become fast and also make jerky.

When user tries to scroll mid-animation, flickering occurs as scrollTo fights the scrollbar

There are two possible solutions - either 1) ignore user scrolling until the animation is complete, or 2) cancel the animation so the user regains control. I'm not sure how easy 1) would be to implement, but 2) is very simple, as the following function demonstrates:

function polite_scroll_to(val, duration, callback) {
    /* scrolls body to a value, without fighting the user if they
       try to scroll in the middle of the animation. */

    var auto_scroll = false;

    function stop_scroll() {
        if (!auto_scroll) {
            $("html, body").stop(true, false);
        }
    };
    $(window).on('scroll', stop_scroll);

    $("html, body").animate({
        scrollTop: val
    }, {
        duration: duration,
        step: function() {
            auto_scroll = true;
            $(window).one('scroll', function() {
                auto_scroll = false;
            });
        },
        complete: function() {
            callback && callback();
        },
        always: function() {
            $(window).off('scroll', stop_scroll);
        }
    });

};

axis scrolling isnt working for me

I have an element at the top left corner of the screen called .pageHome and one way off to the right and down called '.RIGHT'. When i click the link to take me to .RIGHT everything works fine but when I click the Home Link the page jumps to the top (y axis) then scrolls to the left (x axis) even though i am using axis method telling it to scroll x first then y.

Source Here: http://pastebin.com/2bqFZV4R

Missing version tag for Bower for 1.4.5b

It appears the latest version in the component.json (1.4.5b) hasn't been created as a tag, and therefore Bower doesn't recognize it. The current version 1.4.4 has a bug that was fixed that was including the minified version of the file which throws off the grunt-bower task. I fixed this locally with:

git tag -a 1.4.5b -m 'Bower tag version v1.4.5b'

But realized you can't create a pull request for a tag. In the meantime I've configured my project's component.json to point at my fork via:

"jquery.scrollTo": "git://github.com/cbumgard/jquery.scrollTo.git#1.4.5b",

Thanks,

-Chris

Is this Due to Jquery

Uncaught TypeError: Object function (e,t){return new v.fn.init(e,t,n)} has no method 'scrollTo' asset.php:598
(anonymous function) index.php:598
v.event.dispatch jquery.min.js:2
o.handle.u
jQuery v1.8.3

$("nav ul li a").click( function(e) {
var id = $(this).attr("href");
var t = "div";
var total = t+id;
console.log($.scrollTo( $(total), 2000, {offset:-250} ));
});
Getting this error is the call right??

compatible with jQuery 1.10.2?

Is the latest version of scrollTo compatible with jQuery 1.10.2?

I tried scrollTo with jQuery 1.10.2 and could not get it to work. It worked with jQuery 1.8.0. Perhaps I'm initializing the plugin incorrectly?

horizontal scrolling not working in safari 6?

Having an issue in safari 6 on os x mountain lion. For example, when trying to issue a scrollTo() command in a 2000/2000px html body, only the vertical component is scrolled. Is anyone else experiencing this? It works find in safari 5, ie9, firefox and chrome.

$.scrollTo({left:1000, top:1000}, 1000);

Triggering a +1 and -1 scroll.

Hello,

I use the following function to trigger a +1 and -1 scroll using jQuery in order to make images show up when using lazyload in combination with isotope or else the images wouldn't show up when filtering. The website is my portfolio at http://www.gablabelle.com/, click click open the menu and click on Nightlife.

function forceLoad(){
    $.scrollTo("+=1px");
    $.scrollTo("-=1px");
};

It works great in FF and Chrome browsers but not in Safari (testing with version 6).

Using a setTimout works but we can see it scrolling. It has to be transparent for the user.

function forceLoad(){
        $.scrollTo("+=1px");
        setTimeout(function(){
            $.scrollTo("-=1px");
        }, 500);
    };

Any ideas on what I could try to solve this? Or a workaround that also works in Safari?

Stopping a scrollTo animation

This line of code below works great for stopping a scrollTo animation on the body, but when using scrollTo to animate an element buried in the markup, it doesn't seem to stop or dequeue animations. Any ideas?

jQuery.scrollTo.window().queue([]).stop();

Pause and cancel .scrollTo() on `scroll mousewheel DOMMouseScroll` during the `.scrollTo()` animation

How to pause and cancel .scrollTo() on user mousewheel DOMMouseScroll during the .scrollTo() animation like for $('html, body').scrollTo(10000, 10000);?
Probably it would be counted also like a preferred UX feature under the plugin core defaults.

  $(window).on("mousewheel DOMMouseScroll", function(e){
       $.scrollTo.window().stop(true);
  });

it would not work with jQuery event scroll, it handles also mouse click or drag on the scroll bar.

newer (e.g. 31) Chromes complain about what to scroll

body.scrollTop is deprecated in strict mode.
Please use 'documentElement.scrollTop' if in strict mode and 'body.scrollTop' only if in quirks mode.
jquery.scrollTo-amd.min.js:1

Please distinguish between old and new webkits.

(and you may use "use strict";)

sroll up and down

Hello

I tried your srcrollTo plugin for a navigation. "localScroll" was not working at all, so I got it managed to use srollTo for scrolling to an element.

But for now the scrolling always happens from top, is it possible that the scroll scrolls up if the offset is above the current location on the window?

Thanks
Dominic

onBefore callback

Is there a reason localScroll has an onBefore, this one has onAfter, but not onBefore?

Scroll rollout "onAfter" function run in webkit

Please check it here: http://jsfiddle.net/qstdT/9/
Make result panel big as you can and then check it.
Menu(light orange box) is under big red div in which I applied scroll.
Functionality is like, when I click on menu it scrolls and then jQuery's fadeOut & faceIn effects run.
Bug: After this both effects, window automatically scrolls at it's default position.

Animated scrolling suddenly stopped working in chrome

The code below suddenly stopped working in google chrome (it works on firefox and opera) The javascript console has no errors, and if i return true on click, browser jumps to id location, but only after the 750ms delay. Some advice or misusing of your plugin? thanks in advance.

    <script>
        // automatic scroll between anchors in the same page
        $('a[href^="#"]').click(function(event){
            var anchor = $(this);
            var hash   = anchor.attr('href');
            if(hash.length > 1){
                $.scrollTo(
                    hash, 
                    750, 
                    {
                        easing:'easeInOutCubic', 
                        onAfter: function(){
                            window.location.hash = hash;
                        }
                    }
                );
                return false;
            }
        });
    </script>
    <body>
        <a  href = '#about'>about</a>
        <a href = '#articles'>articles</a>

        <section id='about' style='border: 1px solid red; height:2000px'>
            about section
        </section>
        <section id='articles' style='border: 1px solid blue;'>
            articles
        </section>
    </body>

Windows Phone 7 Issue

I am using jq1.10.2, jq-scrollto, jq-nicescroll and some custom jquery to create a single page, responsive wordpress theme.

I am almost done and ready to release the theme, here's a demo http://swgserv.com/web/j/akshaykumar/ it works on all major browsers down to ie7... it works on screens below 800px wide [yeah just 2 stops for now]..

Only problem, which a client pointed out is IE Mobile support - it displays fine but menu which is .scrollto powered isnt. I dont own a test device so I just relied on a video sent to me. Hope you guys can help me out, I tried validating the code as much as I can against HTML5, UTF-8 W3C standards still got some errors but those are from wp plugins and some inner content.

Thanks

Option for not scrolling parent if child is still in view?

Hi there,

Your plugin is great, but I wonder if it would be possible, when scrolling a parent to a child element, to not scroll the parent if the child is still in view. When using the plugin to navigate down a scrolling dropdown menu via the keyboard you currently get the unnatural behaviour that the currently selected item stays at the top of the portion of the list in view - this works but it looks kind of odd when you compare it to standard scrolling behaviour on other elements.

Any thoughts?

Cheers, Andrew.

Update core animate() to allow additional functionality

At its heart, jquery.scrollTo uses this format of the .animate() method:

.animate(properties [, duration ] [, easing ] [, complete ])

Would it be possible to use the alternate version of the .animate() method:

.animate(properties, options)

to allow optional passing in of additional properties that could be animated while the scroll is happening? For example, animating (with the proper plug-ins) the background color of an element while it scrolls.

It appears on cursory examination that this would involve moving the current duration, settings.easing, and callback arguments to a new options object as well as getting the current attr argument into a new properties object along with any other properties that are passed into the plug-in.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.