Code Monkey home page Code Monkey logo

smoothstate.js's Introduction

smoothState.js

smoothState.js is a jQuery plugin that progressively enhances page loads to give us control over page transitions. If the user's browser doesn't have the required features, smoothState.js fades into the background and never runs.

demo of smoothstate

Build Status Gitter

Built with smoothState.js

Below are some cool sites built with smoothState.js. Feel free to submit a pull request with your own site, or tweet me with a link.

Contributor demos

Live Sites

Need help?

If you need a little help implementing smoothState there are a couple things you could do to get some support:

  1. Post on stackoverflow using the smoothState.js tag.
  2. Join the Gitter room and talk to some of the contributors.
  3. Contact Miguel directly, he provides pair-programing help billed by the hour

Please avoid creating a Github issue with personal support requests, to keep the tracker clear for bugs and pull requests.

Intro

Imagine, for a second, how disorienting it would be if touching a doorknob teleported you to the other side of the door. Navigating the web feels like using a teleporting doorknob. Layouts change, elements rearrange or disappear, and it takes time for the user to adjust. Smooth transitions reduce the effort it takes for users to get settled into a new environment.

Javascript SPA frameworks, sometimes referred to as MVC frameworks, are a common way to solve this issue. These frameworks often lose the benefits of unobtrusive code. Writing unobtrusive javascript gives us more resilience to errors, and improved performance and accessibility.

How does smoothState.js work?

smoothState.js provides hooks that can be used to choreograph how elements enter and exit the page during navigation. It uses the time the animations are running to fetch content via AJAX to inject into the page.

smoothState.js doesn't dictate how things on the page should be animated. It supports CSS animations, as well as JS animation libraries like velocity.js.

Design philosophy and requirements

The project's main goal is to allow developers to add page transitions without having to add any logic to the backend. We keep things unobtrusive at all times.

smoothState.js initializes on containers, not links. Think of a container as a small window object embedded in the page.

  1. Every URL on your site should return a full layout - not just an HTML fragment
  2. The smoothState container needs to have an id set - a unique hook to tell us what to update on the page
  3. All links and forms on the page should live within the container

These requirements makes the website resilient, since it smoothState.js can abort and simply redirect the user if an error occurs. Making each link return a full page also ensures that pages are created with progressive enhancement in mind.

Getting started

All we need to do to get started is:

  1. Include a copy of jQuery and jQuery.smoothState.js on your page
  2. Add a container with an id of #main and include some links inside of it
  3. Create a new js file and run $('#main').smoothState()
$(function() {
  $('#main').smoothState();
});

By default, smoothState.js will:

  • Prevent links and forms from triggering a full page load, if possible
  • Use AJAX to request pages and replace the content appropriately
  • Update URLs and browsing history so that browsing expectations aren't broken

smoothState.js will not add page transitions to pages. You'll need to define the animations you want to run using the hooks smoothState.js provides.

  • onBefore - Runs before a page load has been started
  • onStart - Runs once a page load has been activated
  • onProgress - Runs if the page request is still pending and the onStart animations have finished
  • onReady - Run once the requested content is ready to be injected into the page and the previous animations have finished
  • onAfter - Runs after the new content has been injected into the page and all animations are complete

Options

smoothState.js provides some options that allow customization of the plugin's functionality. The default options are overridden by passing an object into the smoothState function.

Options example

$(function(){
  'use strict';
  var options = {
    prefetch: true,
    cacheLength: 2,
    onStart: {
      duration: 250, // Duration of our animation
      render: function ($container) {
        // Add your CSS animation reversing class
        $container.addClass('is-exiting');

        // Restart your animation
        smoothState.restartCSSAnimations();
      }
    },
    onReady: {
      duration: 0,
      render: function ($container, $newContent) {
        // Remove your CSS animation reversing class
        $container.removeClass('is-exiting');

        // Inject the new content
        $container.html($newContent);

      }
    }
  },
  smoothState = $('#main').smoothState(options).data('smoothState');
});

debug

If set to true, smoothState.js will log useful debug information to the console, instead of aborting. For example, instead of redirecting the user to a page on an error, it might log:

No element with an id of “#main” in response from “/about.html”.
// Default
$('#main').smoothState({ debug: false });

anchors

A jQuery selector specifying which anchors within the smoothState element should be bound.

// Default
$('#main').smoothState({ anchors: 'a' });

hrefRegex

A regular expression to specify which anchor with a specific href property based on the regex smoothState should bind to. If empty, every href will be permitted.

// Default
$('#main').smoothState({ hrefRegex: '' });

forms

A jQuery selector specifying which forms within the smoothState element should be bound.

// Default
$('#main').smoothState({ forms: 'form' });

allowFormCaching

Controls whether or not form submission responses are preserved in the cache. If set to true, smoothState will store form responses in the cache. This should be set to false unless you understand how caching form results will affect your website's behaviour very well.

// Default
$('#main').smoothState({ allowFormCaching: false });

repeatDelay

The minimum number of milliseconds between click/submit events. User events ignored beyond this rate are ignored. This can be used to ignore double-clicks so that the user's browser history won't become cluttered by incompleted page loads.

// Default
$('#main').smoothState({ repeatDelay: 500 });

blacklist

A jQuery selector specifying which elements within the smoothState element should be ignored. This includes both form and anchor elements.

// Default
$('#main').smoothState({ blacklist: '.no-smoothState' });

prefetch

There is a 200ms to 300ms delay between the time that a user hovers over a link and the time they click it. On touch screens, the delay between the touchstart and touchend is even greater. If the prefetch option is set to true, smoothState.js will begin to preload the contents of the URL during that delay. This technique will increase the perceived performance of the site.

// Default
$('#main').smoothState({ prefetch: false });

prefetchOn

The name of the events to listen to from anchors when prefetching.

// Default
$('#main').smoothState({ prefetchOn: 'mouseover touchstart' });

If you would like to throttle the prefetch, do so by firing custom events.

Libraries like @tristen's hoverintent can be used to throttle prefetching based on the user's intent, by triggering a custom intent event. To use it with smoothState.js, set intent as the prefetchOn option.

$('#main').smoothState({ prefetchOn: 'intent' });

Or, for the opposite effect, use something like @cihadturhan's jQuery.aim and add spider sense-like prefetching to smoothState.js.

$('#main').smoothState({ prefetchOn: 'aim' });

locationHeader

A field name to lookup among the headers from the HTTP response to alert smoothState.js of any redirected URL.

smoothState.js makes AJAX requests using XMLHttpRequest, which silently follows redirects. This transparence prevents smoothState.js from knowing if a request resulted in a redirection.

For example, when you visit /about and the server redirects you to /about/company, smoothState.js is only ever informed of a successful response from /about. The locationHeader option gives smoothState.js a HTTP response header to consult and replace the browser's history entry with the real URI.

$('#main').smoothState({ locationHeader: 'X-SmoothState-Location' });

cacheLength

The number of pages to cache. smoothState.js can cache pages in memory, avoiding the user having to request pages more than once. Cached pages will load instantaneously.

// Default
$('#main').smoothState({ cacheLength: 0 });

loadingClass

The class to apply to the body while a page is still loading, unless the page is received before the animations are complete.

// Default
$('#main').smoothState({ loadingClass: 'is-loading' });

scroll

Scroll to top after onStart and scroll to hash after onReady. This is default behavior, if you want to implement your own scroll behavior, set scroll: false

// Default
$('#main').smoothState({ scroll: true });

alterRequest

A function to alter a request's AJAX settings before it is called. This can be used to alter the requested URL, for example.

// Default
$('#main').smoothState({
  // Param `request` is an `Object` that is currently set to be used
  alterRequest: function(request) {
    // Must return and `Object` that will be used to make the request
    return request;
  }
});

alterChangeState

A function to alter a history entry's state object before it is modified or added to the browser's history. This can be used to attach serializable data to the history entry, for example.

// Default
$('#main').smoothState({
  // Param `state` is an `Object` that contains the container ID, by default
  alterChangeState: function(state) {
    // Must return a serializable `Object` that is associated with the history entry
    return state;
  }
});

onBefore

The function to run before a page load is started.

// Default
$('#main').smoothState({
  // `$currentTarget` is a `jQuery Object` of the element, anchor or form, that triggered the load
  // `$container` is a `jQuery Object` of the the current smoothState container
  onBefore: function($currentTarget, $container) {}
});

onStart

The function to run once a page load has been activated. This is an ideal time to animate elements that exit the page and set up for a loading state.

// Default
$('#main').smoothState({
  onStart: {
    // How long this animation takes
    duration: 0,
    // A function that dictates the animations that take place
    render: function ($container) {}
  }
});

onProgress

The function to run only if the page request is still pending and onStart has finished animating. This is a good place to add something like a loading indicator.

// Default
$('#main').smoothState({
  onProgress: {
    // How long this animation takes
    duration: 0,
    // A function that dictates the animations that take place
    render: function ($container) {}
  }
});

onReady

The function to run when the requested content is ready to be injected into the page. This is when the page's contents should be updated.

// Default
$('#main').smoothState({
  onReady: {
    duration: 0,
    // `$container` is a `jQuery Object` of the the current smoothState container
    // `$newContent` is a `jQuery Object` of the HTML that should replace the existing container's HTML.
    render: function ($container, $newContent) {
      // Update the HTML on the page
      $container.html($newContent);
    }
  }
});

onAfter

The function to run when the new content has been injected into the page and all animations are complete. This is when to re-initialize any plugins needed by the page.

// Default
$('#main').smoothState({
  onAfter: function($container, $newContent) {}
});

Methods and properties

smoothState provides some methods and properties, made accessible through the element's data property.

// Access smoothState
var smoothState = $('#main').smoothState().data('smoothState');

// Run method
smoothState.load('/newPage.html');

Properties

href

The URL of the content that is currently displayed.

cache

An object containing the cached pages after they are requested.

Methods

load(url)

This loads the contents of a URL into our container.

fetch(url)

This fetches the contents of a URL and caches it.

clear(url)

This clears a given page from the cache. If no URL is provided it will clear the entire cache.

restartCSSAnimations()

This restarts any CSS animations applying to elements within the smoothState container.

FAQ

Help! My $(document).ready() plugins work fine when I refresh but break on the second page load.

smoothState.js provides the onAfter callback function that allows you to re-run your plugins. This can be tricky if you're unfamiliar with how AJAX works.

When you run a plugin on $(document).ready(), it's going to register only on elements that are currently on the page. Since we're injecting new elements every load, we need to run the plugins again, scoping it to just the new stuff.

A good way to do this is to wrap your plugin initializations in a function that we call on both $.fn.ready() and onAfter. You'll want to specify the context each time you initialize the plugins so that you don't double-bind them. This is called a "module execution controller".

Contribute

We're always looking for:

  • Bug reports, especially those for aspects with a reduced test case
  • Pull requests for features, spelling errors, clarifications, etc.
  • Ideas for enhancements
  • Demos and links to sites built with smoothState.js

smoothstate.js's People

Contributors

rolandschuetz avatar digitalmachinist avatar lpodolski avatar mcaskill avatar erbridge avatar igoratsok avatar luminusdev avatar timoschwarzer avatar tobaco avatar phpmagpie avatar kalabasa avatar jbellsey avatar jasonheecs avatar cnkevinlee avatar pudgereyem avatar timgates42 avatar rainloop avatar miguel-perez avatar weefa avatar bfncs avatar leocolomb avatar kkirsche avatar jeremybarbet avatar jorisvm avatar jonathanzong avatar infuzion avatar geldmacher avatar danijelgrabez avatar

Stargazers

 avatar Nyx Shade avatar  avatar Mrinal Chandra Sarkar avatar  avatar Onur avatar Aditheo avatar 刘圣凯 avatar IQBAL HASAN avatar Matt Seligman avatar Alex Majewski avatar Ivan Grimm avatar Adan Alvarado avatar ANSIMA Elvis avatar Cherng Lin avatar  avatar Faisal Ramdan avatar  avatar JulienEQUIUM avatar Masoud Ehteshami avatar Max avatar  avatar Tanner avatar Fefe_du_973 avatar Johnny hong avatar  avatar hemant mudgil avatar KamalkaNipun avatar Sefa AYDIN avatar Sissel avatar Andy Wilkerson avatar Gregor Terrill avatar Ernst Salzmann avatar jvoiture avatar  avatar  avatar Ersoy Filinte avatar  avatar Alexander Boev avatar lsrweb_two avatar Omar fouad avatar Amanda Benade avatar  avatar Zubayr Ali avatar  avatar 【Sid】 avatar Corcules avatar Falko Müller avatar  avatar rxdy avatar  avatar  avatar  avatar xochitljohnson avatar Guilherme Parmezani avatar Gökhan Çelebi avatar Karam Mannai avatar  avatar Ikhsan Hadi Nugroho avatar  avatar Sofia Dinatolo avatar  avatar  avatar Brendan Azzano avatar Graeme Bryson avatar Kamlesh Panchal avatar Caique avatar Eren Yasa avatar Ole Trenner avatar LuckyDeer avatar Mun avatar  avatar Andrew Gerasimow avatar Clark Kent avatar ghJG avatar Dmitry Levchenko avatar  avatar Mohamed Bahaa avatar Francesco avatar Mārtiņš Dāvis Jembergs avatar André Schwarzer avatar Noah Hendlish avatar Kirill Trubetskoy avatar Masahito Nakai avatar David  Bumbeishvili avatar Shubham Ashish avatar Daniel Weidner avatar Matvei P. avatar sean avatar Oleg avatar PERRON UK avatar Mohamed Abdul Kader avatar Cavalier avatar Jefferson Matos avatar  avatar  avatar Radu Paraschiv avatar Matt Gleeson avatar 雷通达 avatar Zineb avatar

Watchers

Omar Dixon avatar Maciej Kuś avatar Victor Sanchez avatar Emanuel Limeira avatar Paul Matunog avatar Chris R. avatar Kaan Karakaya avatar KennethPCF avatar Yuan Chuan avatar  avatar send2vinnie avatar Franklyn avatar Junheon Lee avatar Christian Hochfilzer avatar Shahrukh A. Khan avatar Felix Hirschfeld avatar Lam Nguyen avatar Julian Cataldo avatar Michal Kechner avatar kplus avatar Didier G. avatar Jonath Lee Eng Sing avatar Andrew Minton avatar  avatar Noriyuki Shimizu avatar Bruno Pouliot avatar  avatar Yashi Lanka avatar jeremy buller avatar Raik Ilves avatar  avatar Stefano Zoffoli avatar Eilvein avatar Burak Arslan avatar Dmitry Pronin avatar ᴀʀᴄʜɪᴇ ᴍᴀᴋᴜᴡᴀ™ avatar Babs Gösgens avatar Wilfried Santer avatar Rasha Noureldin avatar  avatar Denis Stoyanov avatar Marcos Menegazzo avatar Michael Anthony avatar AudioVoyeur avatar  avatar Ricardo Palermo avatar Tony Brown avatar Amin Amanpour avatar Steph Charbo avatar JT Thurston avatar cav_dan avatar 肖和龙 avatar  avatar Mustafa ismail avatar Juwel Khan avatar Vesa Virlander avatar Dorian avatar  avatar Nino Ross Rodriguez avatar  avatar Fahim avatar Patric Sterrantino avatar  avatar Son Pham avatar Veselin Hadjiev avatar Carabineiro avatar Pavel R avatar Ali avatar Remco Megelink avatar Rafał Konofalski avatar  avatar Bertrand de Bodinat avatar  avatar jon avatar Tiago Reis avatar peerathai puapan avatar Paweł P. avatar Žiga Vajdič avatar Bora ALAP avatar Younis avatar NO BO avatar José Junior avatar  avatar K.H.U.R.R.A.M avatar  avatar Fahim Akhtar avatar Walter Havelaar avatar Angel Li avatar Jay Mandell avatar Himanshu Pant avatar luqingxuan avatar Andry Gaffar avatar  avatar  avatar Juliette avatar Nikos avatar jayr mendoza avatar Anthony Collins avatar  avatar Anna avatar

smoothstate.js's Issues

toggleClassAnimation not firing

The is-exiting class is not being added to the DOM, unless I put the function inside a .ready(), In which case the entire page flickers.

;(function($){
   var $body = $('html, body'), // Define jQuery collection
   content  = $('#scene').smoothState({
      prefetch: true,
      pageCacheSize: 1,
      development : true,
      onStart : {
         duration: 250,
         render: function (url, $container) {
            content.toggleAnimationClass('is-exiting');
            // Scroll user to the top
            $body.animate({ 'scrollTop': 0 });
         }
      },
      onEnd : {
          duration: 0, // Duration of the animations, if any.
          render: function (url, $container, $content) {
              $body.css('cursor', 'auto');
              $body.find('a').css('cursor', 'auto');
              $container.html($content);
              $(document).ready();
              $(window).trigger('load');
              initialize();
          }
      }
   }).data('smoothState');

})(jQuery);

How to integrate SmoothState with Wordpress at all?

There are few problems with that.

There is one of you that have a complete and serious guide?

For example: I use in my Wordpress both "Visualizer" plugin (that visualize Google Charts in my pages) and "DataTables" plugin of jQuery.

Both aren't working when I use SmoothState.

When I call a page in wordpress that contain one of these from my home page nothing works. The page is blank. Without code. If I refresh browser on that page then everything works.

I suppose the problem is with ajax call of the plugins, but I'll never find a solution. That's why I'm here asking you...

HOW TO?

Can links outside of content area trigger smoothState?

I have a navigation that appears outside of the content that smoothState refreshes. Is there a way to get the links in my header > nav to load and update the content in main?

<header>
    <nav>
        <ul>
            <li><a href="about.html"></li>
        </ul>
    </nav>
</header>

<main class="site-content">
    <article>
        <p><a href="another-page.html">Another link</a></p>
    </article>
</main>

And here's the JS

(function($) {
    'use strict';
    var $body = $('html, body'),
        content = $('.site-content').smoothState({
            onStart: {
                duration: 250,
                render: function (url, $container) {
                    content.toggleAnimationClass('is-exiting');

                    $body.animate({
                        scrollTop: 0
                    });
                }
            }
        }).data('smoothState');
})(jQuery);

Invalidating cache

Do we need a solution for invalid caches?

Example:
An user is using a shop system. The merchant changes product data of an product the user just saw seconds ago. If there is no smoothState.js the user just gets new version of this product the next time he return. With smoothState.js the user gets the old version. Am i wrong with this?

If not, how can we handle this? Just say, that for example shop system should not use smoothState.js or do we need some sort of request which asks the server if the local cache is still valid?

Cross - Browser Problem

First of all: Great idea and great script, but i am experiencing issues with browsers other than Chrome.

In Firefox the following happens:
firefox-issue

In Safari / Webkit the animations do not trigger at all (this may be for me being a noob).

System is OS X 10.9.4 with Chrome 36, Firefox 31, Safari 7.0.6

Sorry if those issues are my failure.

Problem with hash-anchors + back-button

Hey, first off - i love your plugin! But i found an issue when also using on-site hash links, which is crucial for my project right now.

For example, if you are on the demo page http://weblinc.github.io/jquery.smoothState.js/index.html , click a link and press the back button, everything is fine!

However, if the origin url also has a hash attached like this: http://weblinc.github.io/jquery.smoothState.js/index.html#main , you click a link and then the backbutton - nothing happens!

Question: preprocessing?

I'm using a CMS that makes it impossible to render the HTML exactly as I'd like. My goal is to apply smoothState to the body, but I can't give it an ID from my CMS. So I need to apply some jQuery code to get IDs and classes installed, as shown here:

<body>      <!-- need to apply class & ID for smoothState wrapper -->
   <div id="header">...</div>     <!--  need to apply class for transitions -->
   <div id="content">...</div>     <!--  need to apply class for transitions -->
</body>

Any ideas on how to get the ID on the body tag before smoothState processes the page? I've tried adding the jQuery code just about everywhere I can think of: before calling smoothState(), inside onStart, inside onEnd.

Adding the transition classes on the other elements (header and content above) does not present a problem. Just the wrapper.

is-exiting not working

The reversal of the animation does not work for me. In FireFox, it will work if I click the same link again, whilst the initial animation is loading. Here's my code:
SCSS:

.is-exiting {
    .scene__element {
        animation-direction: alternate-reverse;
        -webkit-animation-direction: alternate-reverse;
    }
}

smoothState:

window.onload = function() {
    pageScripts();

    var $body = $('html, body'); // Define jQuery collection 
    var content = $('#main').smoothState({
        prefetch: true,
        development: true,
        onStart : {
            duration: 1000,
            render: function (url, $container) {
                content.toggleAnimationClass('is-exiting');
                console.log("rendering");
                $body.animate({ 'scrollTop': 0 });
            }
        },
        onEnd : {
            duration: 0, // Duration of the animations, if any.
            render: function (url, $container, $content) {
                $body.css('cursor', 'auto');
                $body.find('a').css('cursor', 'auto');
                $container.html($content);
                pageScripts();
            }
        }
    }).data('smoothState');
};

How to use with ASP.NET??

I've been trying for several hours, but I can't make it work with ASP.NET.

It seems that the javascript is not working...

If I set it so the main container is before the "form" (or even the form) element, it works... almost... because it always fails to load images, some styles and scripts...

If I set it up so the main container is within the form, it doesn't work... not even if I execute the script manually, all the events are never called.

Any help would be very much appreciated

npm, bower or cdn?

Is smoothState on npm or some public cdn?

What about adding it to http://cdnjs.com/ (i guess then it has to be a npm package)? Just for quick development hacking around.

Maybe not worth the time. Who knows.

Plugin fails to abort when pushstate is not avaliable

Hi, I'd first like to say I love this plugin, the best I have used so far.

I am however, seeing a bug. The plugin is failing to abort if the browser dosen't have pushstate support.

here's how I am currently calling the plugin:

if(Modernizr.history){
        var $body = $('html, body'); // Define jQuery collection 
        var content = $('#main').smoothState({
            prefetch: true,
            pageCacheSize: 5,
            development: true,
            onStart : {
                duration: 500,
                render: function (url, $container) {
                    content.toggleAnimationClass('is-exiting');
                    console.log("rendering");
                    $body.animate({ 'scrollTop': 0 });
                }
            },
            onEnd : {
                duration: 0, // Duration of the animations, if any.
                render: function (url, $container, $content) {
                    $body.css('cursor', 'auto');
                    $body.find('a').css('cursor', 'auto');
                    $container.html($content);
                    pageScripts();
                }
            }
        }).data('smoothState');
    }

Help with usage of new codebase

As you are aware from comments on my PR #10 I had everything working then realised I was working from an old codebase.

I was using the "typical implementation" method you posted at https://gist.github.com/miguel-perez/7f7443e50fe89bbc2849, and I'm struggling to get the same effect now you've refactored the code.

How do I reliably apply an animation to the incoming content after the outgoing animation has completed? I have tried adding toggleAnimationClass("smoothstate-entering") into "onEnd" but it seems to start before the toggleAnimationClass() call in onStart has finished and things go a bit mad.

Conflict Issue

EDITED:

OK, I've edited my request for help because the last one wasn't very specific :)

I've got this installed and working beautifully in a WordPress site I'm building.
Animations and everything is working great. The site uses InfinateScroll, a basic Timer CountDown script and a js mobile menu (amongst others). I'm getting issues with these when using SmoothState.

Basically when you navigate to a page using either feature, they don't work unless the page is refreshed? Below, I've pasted the code I'm using to load the script - It also uses the fix from Alan Parsons.

Any help would be great, thanks.

///////////////////////////////
// SmoothState
///////////////////////////////
(function($) {
    var $body = $('html, body'),
    content = $('#page').smoothState({
        prefetch: true,
        pageCacheSize: 4,
        onStart: {
            duration: 250,
            render: function (url, $container) {
                content.toggleAnimationClass('is-exiting');
                $body.animate({
                    scrollTop: 0
                });
            }
        },
        onEnd : {
            duration: 0,
            render: function (url, $container, $content) {
                $body.css('cursor', 'auto');
                $body.find('a').css('cursor', 'auto');
                $container.html($content);
                $(document).ready();
                $(window).trigger('load');
            }
        },
        onAfter : function(url, $container, $content) {
        }
    }).data('smoothState');
})(jQuery);

///////////////////////////////
// jquery.ready fix
///////////////////////////////
(function($, undefined) {
    var isFired = false;
    var oldReady = jQuery.fn.ready;
    $(function() {
        isFired = true;
        $(document).ready();
    });
    jQuery.fn.ready = function(fn) {
        if(fn === undefined) {
            $(document).trigger('_is_ready');
            return;
        }
        if(isFired) {
            window.setTimeout(fn, 1);
        }
        $(document).bind('_is_ready', fn);
    };
})(jQuery);

On IE 11 and 10 (perhaps below) animation events are fired endlessly

See the Demo: http://miguel-perez.github.io/jquery.smoothState.js/index.html

If you go to: http://miguel-perez.github.io/jquery.smoothState.js/getting-started.html and click on http://miguel-perez.github.io/jquery.smoothState.js/index.html again the intro animation is going insane. I'm not sure why this happens. I think that the animation start and end event handling is somehow wrong.

Besides this all animation done with wow.js (http://mynameismatthieu.com/WOW/) and animate.css are repeating endlessly as well.

Doesn't work unless going to .html page

I was thinking I could use this plugin on my sites, but my sites don't have "index.html" in the URL bar. Every link ends with a forward slash. Is it possible to make it work for me?

Jquery versions

Really nice plugin! I was wondering if there was any plan to add support for older versions of Jquery (I am thinking back to 1.7 perhaps). 1.9 is a requirement (tried with 1.7 and it broke) at the moment but I had the thought of porting it as a drupal module if there is interest and 1.9 does not play too well with drupal 7. As a whole it might be a nice feature to integrate it in existing environments.

unable to figure out

Hi,

I created a sample webapp to check the smoothState js,

I really love your concept something similar to AngularJS. I wanted to implement this on my new project.

But I'm unable to get how it works. Can you provide us a git to download?

I created a two web pages namely home.html and about.html, then I did call the function $('#body').smoothState(). When I click on either home.html or about.html then entire page loads.

Whereas in the demo link which you've provided for the Transition stuff. In the console only the div with class .page-content gets changed and nothing happens to other elements.

Please do help me out in providing a git so that it would be very helpful for a better understanding.

Thanks in advance.

Rails gem

This could be a sexy inclusion as a Rails gem, as it'd give the Rails framework that SPA feel.

Anyone want to give it a go?

Usage advice needed

First of all .. thanks for releasing this, once I understand how to use it properly, I'll be using it on various projects :)

I need some help using this on http://precept2.highten.co.uk. The site opens with a bootstrap 3 carousel which allows the user to scroll horizontally through each section's 'splash' type content.

When the user clicks on the down arrow from any carousel item I want smoothState to fetch the relevant section's content, smoothly scroll the carousel up off the screen whilst the new page content scrolls up onto the screen.

  1. I have this working to some extent, but the animation is far from smooth. How do I make this scroll smoothly, giving the illusion that the relevant content was waiting below the carousel all the time and simply scrolls up into the space the carousel was occupying?
  2. When I activate smoothScroll the left and right links in the bootstrap carousel stop working, even thought they have classes of no-smoothstate [edited to correct typo].
  3. Is there a way of only linking smoothstate to specific links? E.g. a whitelist rather than a blacklist?

Thanks, Paul.

triggerAllAnimationEndEvent and requestAnimationFrame

Hi,

Thanks for this awesome work !
I try to play with by adding it in a small project. But unfortunately, it didn't work on my first try.

The fact is I have a window.requestAnimationFrame, which fire animationstart for my container (damn it, why ?). And animationend is never fire after. So (animationCount === 0) ? NEVER ! Grrrrr.

To avoid it, I check the target event. I don't know if it's a good solution, but it works for me.
Is it correct ?

onAnimationStart    = function (e) {
    if ($(e.target).is($element)) {
        e.stopPropagation();
        animationCount ++;
    }
},
onAnimationEnd      = function (e) {
    if ($(e.target).is($element)) {
        e.stopPropagation();
        animationCount --;
        if(animationCount === 0) {
            unbindHandlers();
        }
    }
};

Safari constantly reloading page

Miguel, really digging the concept of this plugin. Been thinking about something like this for a while.

There's an issue with the current version of Safari on OS X (v7.0.5) where it seems the code makes the site constantly reload in the browser. You can see the effect on your personal site.

Haven't dug that far with it yet. I'm definitely following this project!

PJAX

is this a pushstate ajax plugin? if so what happens when pushstate is not supported

<title> not updating correctly in Chrome

Just have to say, this is awesome!
But the title is not updating correctly in Chrome (v 36.0.1985.143). Instead of the given title-tag it sets the url (this is the correct url though) as the title. Any ideas?

Works perfect in Firefox and Safari.

change <head> contents

Hello, Miguel,

First, congrats for this awesome plugin, it's really neat!

I have a quick question. I saw that after every page reload, the <title> tag gets updated, which is great. But lets suppose that a page that would be loaded have different contents inside the <head> (i.e. additional stylesheets, scripts, bla bla bla). Is there a way to inject those contents inside the <head> tag too? Or is there a different approach that you could suggest?

Thanks!

Hash / achor link to another page

I am aware of the back-button issue with anchor links, but what I am trying to do is link to another page with an anchor link. Everything works as expected, except that when you arrive on the new page you are at the top of the page, not at the anchor / hash link location.

Ex: you are on about.html ... and click a link to /contact#form ... but you end up at the top of the "Contact" page, not down at your contact form anchor.

I know the whole hash link on another page thing is not a great UX idea, unfortunately, it's something that someone else wants. Any thoughts if this is possible now, or would support need to be added in a future version?

Thanks! Amazing (game changing I would say) plugin you have here!

Controlling Styles

I think it'd be nice to no longer have to concern myself with cursor styles or "height: auto" if I don't want it. Seems a bit intrusive. Maybe introduce an option to not mess with inline styles? I hate utilizing "!important" in my CSS.

onAfter render function not being called

Hey, on line 395, there's an error where onAfter is being called as a function, but it should be onAfter.render() (I think, as it's bugging for me).

options.onAfter.render(url, $container, $content); seems to fix things!

Support form submissions

Currently smoothState does will allow a page to reload when a form is submitted. We'll want to:

  • Add an event listener for form submission within the smoothState element
  • Add a default "forms" option similar to "anchors"

Uncaught TypeError: Cannot read property 'length' of undefined localhost/myphpproject/js/jquery.smoothState.js:209

I am developing a PHP project where I am trying to use jquery.smoothState.js. I have kept all my contents in

and done all other things properly. When I am clicking Sign in link which is linked to signin.php, it's changing URL to localhost/myphpproject/signin.php, but not replacing current content with Signin.php content. However, if I view source, I can see signin.php is loaded but not displayed in browser. Even I added animate.css classes and it's just animating for a while but not replacing the content. Then I saw the console where I found following error -

Uncaught TypeError: Cannot read property 'length' of undefined localhost/myphpproject/js/jquery.smoothState.js:209

Kindly tell me where I am doing mistake or what is the exact problem.

Only the navigation is reloaded when a link is clicked

First of all thanks for sharing this excellent plugin, the demo site is extremely impressive!

This may be a bug or may be me misunderstanding how this plugin is intended to work, but currently while testing smoothState clicking a link in the navigation only reloads the navigation rather than the entire section. My markup is essentially:

<body>
    <header>
        <h1>My awesome website</h1>
    </header>
    <div id="wrapper">
        <nav id="nav">
            <a href="page1.html">Page 1</a>
            <a href="page2.html">Page 2</a>
        </nav>
        <main id="main">
            <h2>Page 1</h2>
        </main>
    </div>
    <!-- Scripts here -->
</body>

And my script (using velocity.js for animation) looks like this:

(function ($) {
    $('#wrapper').smoothState({
        onStart: {
             duration: 200,
             render: function () {
                 $('#main').velocity('fadeOut', 200);
             }
         },
         onEnd: {
             duration: 200,
             render: function () {
                 $('#main').velocity('fadeIn', 200);
             }
         },
     });
 })(jQuery);

It seems as if smoothState is simply finding the nearest parent of the link with an id and only replacing the inner html there, rather than for the entire wrapper. Is that correct? How could this be changed in order to reload the entire wrapper?

Better yet, could smoothState be configured to reload only the 'main' section when a link is clicked in the 'nav' section?

Thanks,
Alfie

perform JavaScript call on cached page

I have video backgrounds courtesy of YouTube. At the moment I have a custom JQuery plugin that is called from within the page itself (video id is specific to the page content on the page):

<script>
    $('#celeb-profile-video-wrapper').tubular({videoId: '<YT vid id>'});
</script>

The events are only fired when the page is loaded into the container from the cache. Is there a way to get them to run when the content is loaded into the cache i.e. so the background is playing when the content is pulled from the cache to the container.

I hope you understand what I am trying to get at.

Many Thanks,
Paul

Smoothstate.js + Velocity.js

I was trying to use velocity instead of css3 animation, something like below; but somehow it didn't work, any advice?

            onStart: {
              duration: 250, // Duration of our animation
              render: function (url, $container) {
                content.velocity({ fadeIn }, 1000);
              }
            }

I've tried using $content.velocity({ fadeIn }, 1000); but also not working,

Add an option to change the container for anchors

In relation with #35

I wonder if change the container for anchors is interesting.
This can be in the options, if someone needs to have this feature absolutely.

It's easy to implement, I have already test it. But this functionality will require a good documentation to make people understand container for anchors can't be in original container (obviously disappears binding).

So, useful ?

Bug: blank line in wrapper element chokes parser

If the contents of the element passed to smoothState() starts with a blank line, the parser chokes:

<body id="smooth-state-root">

        <h2>My header</h2>
        . . .

This is easily fixed: on line 211, trim the value before wrapping it in $():

updatedContainer = ($insideElem.length) ? $.trim($insideElem.html()) : $html.filter(id).html(),

Occasional Uncaught TypeError

Installed smoothState on a site and got the occasional Uncaught TypeError in Chrome 37.0.2062.76 beta-m, and TypeError: cache[url] is undefined with Firefox 31...

Chrome Console readout:
Uncaught TypeError: Cannot read property 'status' of undefined scripts.js?ver=3.9.2:900(anonymous function)

The exact line referenced is:
responsescache[url].status;

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.