Skip to main content

SimpleSlideView: Controlling Flow With JavaScript

By Tyler Sticka

Published on March 11th, 2014

Topics

In July we released SimpleSlideView, a jQuery and Zepto plugin for simple, responsive sliding views (here’s a demo). In the last few months, I’ve noticed an uptick in developers emailing to ask a variation of this question:

How do I change or stop a view transition based on user input?

It’s a great question, and one that may not be immediately apparent from the demo alone.

When using SimpleSlideView, there are two ways to navigate between views. The simplest way is with HTML, which is great for predictable, non-dynamic interactions or prototyping:

<button data-pushview="#result">See Result</button>
Code language: HTML, XML (xml)

The straightforwardness of this technique is a double-edged sword. It’s easy to use, but it’s also kind of static. What if we want to change the destination? Or prevent the transition altogether? For that, we’ll want to use JavaScript instead.

We can remove the data-pushview attribute from the button, but we’ll need some way to select it via JS, so let’s give it an ID:

<button id="result-btn">See Result</button>
Code language: HTML, XML (xml)

And here’s the scripty part:

// Save the simpleSlideView instance to a variable
var slideView = $('#container').simpleSlideView();
// Add a click event handler to the button
$('#result-btn').click(function(){
  // On click, push the view with an ID of 'result'
  slideView.pushView('#result');
});
Code language: JavaScript (javascript)

Right now this probably feels like a step backward. It’s more verbose. But we’ve gained the freedom to define the sliding-view behavior any way we like.

Suppose you only want to transition when certain criteria are met:

if (isValid) {
  slideView.pushView('#thanks');
} else {
  alert('Oops! Something seems off.');
}
Code language: JavaScript (javascript)

Or maybe you’d like the next view to depend on the value of something else:

if (age < 21) {
  slideView.pushView('#soda');
} else {
  slideView.pushView('#beer');
}
Code language: JavaScript (javascript)

Here’s a working example that uses Moment.js and your browser to determine the weekday of a date you provide. The result is populated before the view transitions, and only if Moment.isValid() returns true:

See the Pen Weekday (SimpleSlideView Demo) by Tyler Sticka (@tylersticka) on CodePen.

For more info on what you can do with SimpleSlideView and JavaScript, refer to the documentation on GitHub. If you’re using SimpleSlideView in your own projects, we’d love to hear about it!

Comments