Giter Site home page Giter Site logo

d4nyll / smartscroll Goto Github PK

View Code? Open in Web Editor NEW
256.0 12.0 46.0 233 KB

jQuery plugin for scrolljacking and auto-hashing

Home Page: https://d4nyll.github.io/smartscroll/

License: MIT License

Ruby 3.96% CSS 11.08% JavaScript 84.96%
jquery-plugin

smartscroll's Introduction

smartscroll

FOSSA Status

smartscroll is a tiny (1815b minfied + gzipped) jQuery plugin that has these independent features:

  1. Section scrolling - Scrolljacking
  2. Auto-hash - Updates the URL hash based on current position on page
  3. Responsive - You can disable scrolljacking below a set breakpoint

It also supports:

  1. Varied Section Heights
  2. Hybrid Scrolling - Both normal and scrolljacking on the same page
  3. Compatible with scrollbar - Can use scrollbar as well as mousewheel
  4. Disabling permalink history
  5. Correctly detects scroll events for inertial scrolling, by integrating with lethargy as a soft dependency (which means it will work without it)
  6. Provides events you can listen to, by integrating with EventEmitter as a soft dependency

Requirements

  1. There can only be one set of adjoining sections

How to Use

Install lethargy, which is available as a Bower package, which you can install with bower install.

Structure your HTML like so (default options included)

<body>
  <div class="section-wrapper">
    <div class="section" data-hash="section-hash-name"></div>
    <div class="section" data-hash="section-hash-name"></div>
  </div>
<script src="path/to/lethargy.min.js">
<script src="https://rawgit.com/Olical/EventEmitter/master/EventEmitter.min.js"></script>
<script src="path/to/smartscroll.min.js">
<script>
  var options = {
    mode: "vp", // "vp", "set"
    autoHash: false,
    sectionScroll: true,
    initialScroll: true,
    keepHistory: false,
    sectionWrapperSelector: ".section-wrapper",
    sectionClass: "section",
    animationSpeed: 300,
    headerHash: "header",
    breakpoint: null,
    eventEmitter: null,
    dynamicHeight: false
  };
  $.smartscroll(options);
</script>
</body>

You may also want to link to styles.css, but all that does is to ensure the html and body elements have no margins nor padding

You may also leave out lethargy, but smartscroll may not work as well with scroll devices that uses inertial scrolling. Performance with lethargy can be slower, but it will be improved with further development.

Options
  • mode - (String) Valid options are:
    • vp (Viewport) - The sections will be automatically sized to be the same as the viewport
    • set - Use the height and width set by CSS (use this for having different heights for different sections)
  • autoHash - (Boolean) Whether the auto-hashing feature is enabled. If you use this feature, it is important to use EventEmitter as well, otherwise smartscroll will listen to every scroll event, which is very resource-draining and can make the animation more 'glitchy'
  • sectionScroll - (Boolean) Whether the section-scrolling feature is enabled
  • initialScroll - (Boolean) Whether smartscroll should scroll to the position specified by the hash on initial load
  • keepHistory - (Boolean) Whether scrolling through different sections will be recorded in the browser's history
  • sectionWrapperSelector - (String) The CSS selector for the block element which wraps around your sections
  • sectionClass - (String) The class name applied to each section
  • animationSpeed - (Integer) Time taken for the scroll animation, in miliseconds
  • headerHash - (String) The hash for the section above the sections, must be non-empty to reliably ensure the page do not jump when updating the hash value across browsers (as # means _top)
  • breakpoint - (Integer) The width of the browser below which scrolljacking will be disabled
  • sectionSelector - (String) The selector applied to each section, overrides sectionClass and allow more flexibility in choosing a selector. (Added in 2.1.0)
  • dynamicHeight - (Boolean) If you are going to be dynamically adding and removing content so as to change the position and/or size of the section wrappers and/or sections, then set this to true. Set to false otherwise to increase performance.
  • eventEmitter - (Object) If you pass in an EventEmitter object, autoHashing will be much more efficient. You can also listen to the scroll events this way. Defaults to null.
  • ie8 - If you need to support Internet Explorer 8, change this to true. Defaults to false.
  • bindSwipe - (Boolean) Allow for listening of swipe events. Requires EventEmitter. Defaults to true
  • bindKeyboard - (Boolean) Allow for keyboard events (up and down arrows) to control slides. Defaults to true

Events

Smartscroll has a soft dependency on EventEmitter. If present, smartscroll can provide six events scrollStart, scrollEnd, swipeLeft, swipeRight, swipeDown and swipeUp. The scrollStart and scrollEnd listener will receive the slide number as its only argument; the first slide will have a number of 1, the section before the sectionWrapper will have a number of 0.

var ee = new EventEmitter();
var scrollStartListener = function (slideNumber) {
  console.log("Scrolling to " + slideNumber);
}
var scrollEndListener = function () {
  console.log("Scrolling End");
}
ee.addListener('scrollStart', scrollStartListener);
ee.addListener('scrollEnd', scrollEndListener);
$.smartscroll({
  ...
  eventEmitter: ee
});

The other listeners receive no arguments.

var ee = new EventEmitter();
var swipeUpListener = function () {
  console.log("Swiping Up");
}
var swipeDownListener = function () {
  console.log("Swiping Down");
}
$.smartscroll({
  ...
  eventEmitter: ee,
  bindSwipe: true
});
ee.addListener('swipeUp', swipeUpListener);
ee.addListener('swipeDown', swipeDownListener);

Manual Scroll

You can manually scroll up or scroll down.

When you first initiate smartscroll with $.smartscroll(), it returns an object. In that object is the scroll function, which is called with a single parameter. If the parameter is truthy, it will scroll down, otherwise, it will scroll up.

var smartscroll = $.smartscroll();
smartscroll.scroll(1);

Architecture

Currently, there are two features of smartscroll, and this is how it's implemented:

  1. Smooth scroll by section

The mousewheel and DOMMouseScroll (for Firefox) events are bound.

When such event is fired in vp mode, smartscroll will find it's most prominent section (one which occupies most of the screen), and smoothly scroll to the section above or below it.

When the event is fired in set mode, smartscroll will find which section occupies the middle of the screen, and smoothly scroll to the section above or below it.

When scrolling outside of the sections, normal scrolling resumes.

  1. Changing URL hash based on the current section

The scroll event is bound.

When the event is fired in vp mode, smartscroll will see which section occupies the top of the viewport, and if the hash is different, replace it with the new one.

When the event is fired in set mode, smartscroll will see which section occupies the middle of the viewport, and if the hash is different, replace it with the new one.

License

FOSSA Status

smartscroll's People

Contributors

d4nyll avatar dependabot[bot] avatar depfu[bot] avatar fossabot avatar franchert avatar pudgereyem 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

smartscroll's Issues

Odd behaviour on initial scroll in Chrome

When I first start to scroll, and I am on the first section. It seems as though regardless of whether I swipe up or down. The page begins to animate as though I am scrolling down. You can see this effect in the demo here (http://d4nyll.github.io/smartscroll/different-heights/). If you scroll up the page will scroll down as though you were scrolling down.

Note this only happens on the initial state. Once you have commenced scrolling you cannot then scroll up and cause the page to scroll down.

Is this an intentional effect? As ideally I would like nothing to happen when scrolling up from the first slide.

Hope that makes sense! For the record I am using a Macbook trackpad to scroll and am seeing this effect in Chrome 49 and Canary, but not in Firefox or Safari.

Mouse wheel scrolling not working in Firefox

I cannot get smartscroll to work in Firefox. Specifically, I cannot scroll a page using the mousewheel.

Without knowing any more info, can anyone validate this problem? I feel the problem is on me, but I've tried all reasonable debugging tactics to no avail.

I've made sure that my HTML is solid - all tags open and close properly.

I've tried stripping away other js plugins but thats not helping.

I am hesitant in providing my code or a link, just because of privacy issues. My apologies for not providing more thorough documentation. However, if anyone has any GENERAL knowledge of this plugin breaking wheel scrolling in Firefox, I will appreciate it.

Thanks for the plugin and documentation!

Add keyboard controls

Namely, up arrow for moving one slide up, and down arrow for moving one slide down.

Integrate with EventEmitter

Emit events after scroll started, is scrolling, and scroll finished. With arguments given to identify the slide.

Doesn't work with visual composer

Hi,
I am trying to implement this in my WordPress app. It works fine when I use it as simple html page in wordpress. But when I use it with visual composer it does not work. Any suggestions for this?

Thank You.

Screen jumps unexpectedly

I was experiencing a bug where the screen would jump to the top of the screen if the scrolling sections were over, and the section coming after was not bigger than the screen's height.

I fixed the issue by adding the check
if(typeof sections[sectionIndexAtWindowMiddle] !== 'undefined')
in the bindScroll function on line 331.

Hope this can help out.

Only need swipeUp & swipeDown event on Trackpads / mousewheels

I am desperately looking for a way to detect a swipe on trackpads and "a single flick" on mousewheels.
Unfortunately I can't find a way to extract these bits out of your code and don't see a way to only use these events from your library.

Of course I have EmitterEvents.js and lethargy.js installed aswell.

Could you please tell me a way to callback only on swipeUp / swipeDown without doing altering anything else?

Hashes are being set 1 section ahead

I've noticed that when you scroll the hash of each section is one ahead. This is happening on my project as well as on the Demo page you set up. Any idea on what's causing this and if there is anyway to fix it? I'm thinking of using this plugin for my next project, but I would need the hashes to be correct. Other than this issue with the hashes, the plugin is pretty awesome!

Any help is appreciated, thanks!

Momentum / Inertia Scrolling

As mentioned in #1, momentum / inertia scrolling means one scroll using a trackpad or the Apple Magic Mouse can actually move through several sections.

Ideally, one scroll action, no matter how big it is, should move through one section only.

This is a similar issue with to this on jquery/jquery-mousewheel. And this demo demonstrates the problem.

Comments, solutions and pull requests welcomed!

Trackpad touch events

Your plugin seems very promising, and if it keeps the promises made in your comparison, then it can be a real alternative to fullPage.js. However, it's impossible for me to implement it before touch trackpads events be supported. Do you plan to implement it soon?

Thanks,

scrollEnd Event returns no slidenumber

Hi,

in your documentation, you write

The scrollStart and scrollEnd listener will receive the slide number as its only argument; [...]

which would be very useful for me ;)
Unfortunately, your version doesn't return a slidenumber at scrollEnd, but "undefined"

I fixed that in a local copy:

smartscroll.js:174

windowTop = getWindowTop();
if (options.eventEmitter) {
  sectionIndexAtWindowMiddle = getSectionIndexAt(windowTop + $(window).height() / 2);
  options.eventEmitter.emitEvent('scrollEnd', [sectionIndexAtWindowMiddle]);
}

Hybrid Scrolling issue

I can't scroll to the portions after the section tagged for hybrid scrolling. It seems that I cannot go beyond the last panel of the section. Is there a fix to this?

URL hash update based on scroll is not working.

I am trying to use this plugin. I see the headerHash appear but it does not update as I scroll. I have attached pictures of what my code looks like and there are no console errors so I know the syntax is not the issue. Please help! Also, I have the three script files included below all my code right before the closing body tag.

<script src="js/lethargy.min.js"></script> <script src="https://rawgit.com/Olical/EventEmitter/master/EventEmitter.min.js"></script> <script src="js/smartscroll.min.js"></script>

screen shot 2017-12-19 at 1 46 04 pm
screen shot 2017-12-19 at 1 46 13 pm

Horizontal scrolling

Hi - thanks for building this library!

I'm looking for a solution that allows me to implement scrolljacking on mobile only for a horizontal list. Something like this example but that scrolls each card one by one, snapping each card into the featured position each time the user scrolls.

Is this something that would be interesting as a new feature for this library? Any suggestions on how I could begin adapting it?

Thanks!

Scrolling with Magic

Hello,
Have you tried to scroll your demo with an Apple Magic Mouse? It's always passing 2 slides each time.

Scroll section with offset

Hi.
I'm looking for a way to add an offset when scrolling down to my section.
I've a fixed header, so my differents section's height is 100vh - header.height().

Is there a way to scroll to the sections with an offset of the header height ?

thanks a lot

Add navigation

Hi,

would like to see this in this plugin. A navigation that refers to the right hashes and the links should get an is-active status when they hit the section.

Here's a snippet of my last implementation of it (no active status is added when the section is hit at the moment):

   /// Navigation Scroll
   /////////////////////////////////////////////////////////////
   var _navHeaderLink = $('.nav-main_item-link');

   _navHeaderLink.each(function(i, elm) {
      var _link = $(elm);

      _link.click(function(e) {
         e.preventDefault();

         var _linkHash = $(this).data('hash-jump');

         // Scroll to the section
         $('html, body').animate({
            scrollTop: $(_linkHash).offset().top
         }, 600, 'easeInQuart')
      })
   });

breakpoint in hybrid scrolling

viewport and sections don't match when hybrid scrolling changes. would be nice if it snaps more accurate. tested on chrome 55.0.2883.95, safari 10.0.2 and firefox 50.1.0 on macOS sierra 10.12.2 with trackpad.

bildschirmfoto 2017-01-10 um 14 11 52

Jittering in Chrome with smooth scrolling on OSX

From Reddit.

Using Chrome with smooth scrolling on OSX (I think the windows version doesn't have smooth scrolling), scrolling along the top of the page - the part without scrolljacking - stutters for some reason. (With Firefox's smooth scrolling it doesn't.)

Scrolling skips frames

When scrolling from the header to the pages, it scrolls three pages in once, Safari, OS X.

CVE-2015-9251 Medium Severity Vulnerability detected by WhiteSource

CVE-2015-9251 - Medium Severity Vulnerability

Vulnerable Library - jquery-1.11.3.min.js

JavaScript library for DOM operations

path: /smartscroll/examples/different-heights-hybrid-scroll/index.html

Library home page: https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js

Dependency Hierarchy:

  • โŒ jquery-1.11.3.min.js (Vulnerable Library)

Vulnerability Details

jQuery before 3.0.0 is vulnerable to Cross-site Scripting (XSS) attacks when a cross-domain Ajax request is performed without the dataType option, causing text/javascript responses to be executed.

Publish Date: 2018-01-18

URL: CVE-2015-9251

CVSS 3 Score Details (6.1)

Base Score Metrics:

  • Exploitability Metrics:
    • Attack Vector: Network
    • Attack Complexity: Low
    • Privileges Required: None
    • User Interaction: Required
    • Scope: Changed
  • Impact Metrics:
    • Confidentiality Impact: Low
    • Integrity Impact: Low
    • Availability Impact: None

For more information on CVSS3 Scores, click here.

Suggested Fix

Type: Change files

Origin: jquery/jquery@b078a62#diff-bee4304906ea68bebadfc11be4368419

Release Date: 2015-10-12

Fix Resolution: Replace or update the following files: script.js, ajax.js, ajax.js


Step up your Open Source Security Game with WhiteSource here

How to do a split screen scroll?

Hi Daniel,

Thank you for smartscrool. It's great! I just wanted to ask if its possible to do a split screen smartscroll. One side is just normal scrolling with some text floating to the left, and another with using smartscroll and images. Whats happening with me now is that even if i dont include the left side text inside the section wrapper it is still affected by the smartscoll being used on the right side. I hope you can help me!

Jumping to top from last section in Hybrid Scrolling

We are seeing some odd behavior when re-entering the section wrapper (scrolling up).

Occasionally, the page will scroll to a point where a few pixels of the last section is visible. When this happens, scrolling back down causing the page to instantly jump to the top of the section wrapper.

Any ideas?

Question: Make `React` version?

Hey @d4nyll, hope you're all good!
I'm thinking of making a smartscroll port for React.js.
Just wanted to ping you about it, if you'd want to discuss that or anything!

Peace!

Cannot read property 'offsetTop'

I tried to use this fantastic plug-in and it works well, as long there is no navigation bar at the top of the site.

When using the bootstrap navigation bar, smartscroll generates the error "Cannot read property 'offsetTop'" on chrome or a "Die Eigenschaft "offsetTop" eines undefinierten oder Nullverweises kann nicht abgerufen werden." (property "offsetTop" of a undefined Null-reference could not be read) on IE.

Is it possible to set an offset for the page top ?

Scroll within a section

For the Different Heights feature, when the section is much taller than the viewport height, scrolling down will take you to the next section, cutting off the rest of the text of the current section that lies 'below' the viewport.

It would be an improvement / feature to allow normal scrolling until you reach the bottom of the current section, and then section scrolling will take effect again.

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.