Simple Optimized Parallax

Parallax – you love it or you hate it, but web designers will incorporate it into new designs regardless. This web design trend has been all the rage over the past few years, with countless javascript libraries existing to help make things a bit easier. However, it can be difficult to customize them to your liking, and sometimes you just want something a bit more lightweight.

In a recent project I ran into something that I hadn’t done before. The designs provided were very precise, but they also were going to be content managed. They wanted parallax on a bunch of the items on screen, but didn’t want the parallax to break their precise designs. With all of the javascript libraries I tried, parallax was calculated by how far you have scrolled down the page, with the transition distance based on that height. This is great and can look cool, but if you have a site of variable height due to being content managed, this wont work. If the page is modified to be shorter or longer than it was when you designed it, by the time you scroll to that parallax element it may be a lot higher or lower than you had intended it to be. I needed a better solution, so I made my own little parallax function for my project utilizing a little jQuery function called isOnScreen, which returns true if a given element has at least 1 pixel within the viewport.

Here’s what I came up with:

$(window).scroll(function(){
  $('.parallax').each(function(){ 
    if ($(this).isOnScreen()) {
      var firstTop = $(this).offset().top;
      var winScrollTop = $(window).scrollTop();
      var shiftDistance = (firstTop - winScrollTop)*0.2;
      $(this).css({"transform": "translate3d(0px, " + shiftDistance + "px, 0px)"});
    }
  });
});

First, I set everything up to run on window scroll. I have attached a parallax class to the element I want to be affected by the parallax effect. Then, I check to see whether or not the element is within the viewport. This means I can be more precise with my parallax effect because I know exactly when it is engaged. I then get the distance of the element to the top of the page, the distance of scroll from the top of the page, and then calculate a distance to shift the element based off of those two variables combined with a multiplier, which determines scroll speed. I then simply apply a translate3d with that shift distance to move the object. This allows us to only run parallax on that element while it’s on screen, optimizing resources for the page and keeping the animations clean. I use transform3d in this case (as opposed to transformY) to tell the browser to engage the graphics card, if possible, resulting in a buttery transition.

 

 

This was a pretty easy approach to parallax that I hadn’t used before, and hopefully will help make your next project go a bit smoother.

Happy coding!

Uncaught TypeError: .sort is not a function ?!

So i’ve done some ajax calls and wanted to sort my results and ran into the error:

Uncaught TypeError: resultData.sort is not a function

This is because the returned data is an object and jQuery’s sort function only works on array. So the solution is to map the object to an array:

var resultArray = $.map(resultData, function(value, index) { return [value]; });
resultArray.sort().reverse();

Now you can sort or manipulate your data as an array!  Easy-peasy.

How Do I Autoplay Vimeo Videos Without Sound?

Using video is a great way to get users on your website engaged with the content. And with video websites like Vimeo you can easily embed content onto your site without having to worry about uploading a large video file. When embedding a Vimeo video there are a handful of options for customization using their oEmbed API and it’s really easy to use by simply adding arguments to the end of the embed source string. If you’re going to use the API arguments, make sure that you enable the API before adding other arguments simply by adding the short string: “?api=1”

A somewhat common feature that is sought after is for videos to autoplay and play continuously. We can accomplish this by adding another string to our source after the enabling the API: “&autoplay=1&loop=1”

Now our source string should look something like this:
src=”https://player.vimeo.com/video/45819280?api=1&autoplay=1&loop=1″

Now our video will play automatically on page load and won’t stop playing until the user pauses it or leaves the page, which is great! But, more often than not, that video has sound playing. And when the user lands on your page, you don’t want to be blasting them with sound from a video that they didn’t start. This can cause a poor user experience and push people away from your site.

To avoid your beautiful video’s sound from scaring people away, we can use a little javascript to set the volume to 0. First, we must include a script from Vimeo’s CDN to allow us to manipulate the video player. Once included, we can write a small function that will listen for the video to be “ready” and set the volume to 0. To target that iframe we will also need to add one last string to the video source called: “&player_id=vimeo_player”

Now our source string should look something like this:
src=”https://player.vimeo.com/video/45819280?api=1&player_id=vimeo_player&autoplay=1&loop=1″

 

<script src="//f.vimeocdn.com/js/froogaloop2.min.js"></script>
<iframe id="vimeo_player" src="https://player.vimeo.com/video/45819280?api=1&player_id=vimeo_player&autoplay=1&loop=1" width="100%" height="150" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
<script type="text/javascript">
    var iframe = $('#vimeo_player')[0],
        player = $f(iframe);

    player.addEvent('ready', function() {
        player.api('setVolume', 0);
    });
</script>

Ajax requests in WordPress

There are many reasons to use Ajax on a website as it allows the content to load into the page as needed.  In the past i’ve always made a separate file for handling all these things, and performance wise they may be about the same. However, there is a built in way to do these things the official WordPress way that was actually easier to work with than creating new services.

WordPress Documentation
Demo example

Summarizing, there is a “wp_ajax_[ACTION]” hook that allows server side processing of the ajax request.

add_action( 'wp_ajax_nopriv_[ACTION]', 'ajax_process_function' );
add_action( 'wp_ajax_[ACTION]', 'ajax_process_function' );
function ajax_process_function() {
	$filterpage = $_REQUEST['page'];
	$filterformat = $_REQUEST['format'];
	echo "Page:".$filterpage." Format:".$filterformat;
	die();
}

This is accompanied by a jQuery ajax request that looks like:

$.ajax({
	url: "/wp-admin/admin-ajax.php",
	type: 'post',
	data: {
		action: '[ACTION]',
		filterpage : 1,
		filterformat : "format"
	},
	success: function( html ) {
		if(html){
			$('#container').html( html );
		}else{
			alert("no content");
		}
	}
});

How do I queue jQuery ajax requests

I was recently doing some javascript testing and needed to make some asynchronous (sequential) ajax requests for authentication, creating of records, etc. As with all good things jQuery, the solution to this problem is to install the plugin. The ajaxq plugin, that is.

Installation is as simple as including it in your code.

[script language="javascript" src="/js/jquery-1.6.2.min.js"][/script]
[script language="javascript" src="/js/jquery.ajaxq.js"][/script]

Then calling the $.ajaxq method, which takes the queue name (use different names to run multiple asynchronous queues synchronously) and the settings object with the same parameters as jQuery’s ajax function.

$(function() {
	//Login, then logout
	$.ajaxq("queue", {
		url: '/api/user/login',
		type: "POST",
		data: { 
			username: "username", 
			password: "password"
		},
		success: function(data) {
			document.write("Logged in...
"); } }); $.ajaxq("queue", { url: '/api/user/logout', type: "POST", success: function(data) { document.write("Logged out...
"); } }); });

And finally, an example which runs two queues simultaneously:

$(function() {
	//Login, then logout
	$.ajaxq("one", {
		url: '/api/requestone',
		type: "POST",
		success: function(data) {
			document.write("Request one queue 'one'...
"); } }); $.ajaxq("two", { url: '/api/user/logout', type: "POST", success: function(data) { document.write("Request 1 queue 'two'...
"); } }); $.ajaxq("two", { url: '/api/user/logout', type: "POST", success: function(data) { document.write("Request 2 queue 'two'...
"); } }); });

Output could either be

Request 1 queue 'two'...
Request 2 queue 'two'...
Request 1 queue 'one'...

or

Request 1 queue 'one'...
Request 1 queue 'two'...
Request 2 queue 'two'...

Custom jQuery “lightbox”

One thing I learned this week was how to make my own “lightbox” in jQuery. I’ve always used tools like thickbox or lightbox, but I’ve never actually needed to change some of it’s functionality. Or for that matter, change the look of it other than a quick color swap or two.

The below code is the main HTML of the light box. It’s quite fantastic because anything inside the “modal-container” div can be styled exactly how you need it without the over-extensive code written for other light-boxes:

Click me to open modal box

Here’s a little CSS to make it invisible on default and set the overlay and container colors:

#overlay, #modal-container{display:none; } 
#overlay{background:#000; width:100%; height:100%; position:fixed; top:0; left:0;  }
#modal-container{background:#fff; width:820px; height:420px; border:3px #ccc solid; top: 10%; left:50%; margin:0 0 0 -420px; position:fixed;filter:alpha(opacity=100);  opacity:1;}

The below code is the main jQuery commands that makes the lightbox appear and go away:

$(document).ready(function(){
	$('#overlay').click(function() {
		$('#overlay').fadeOut();
		$('#modal-container').fadeOut();
		return false;
	});
	
	$('.modeBoxLink').click(function() {
		$('#overlay').fadeIn(1000);
		$('#modal-container').fadeIn(1000);
		return false;
	});
});

So if you have a link on the main page with class set to “modeBoxLink” it will open up the box you just created! Good for whatever content you need in such a window. ((Don’t forget to include the jQuery library))

All together:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$('#overlay').click(function() {
		$('#overlay').fadeOut();
		$('#modal-container').fadeOut();
		return false;
	});
	
	$('.modeBoxLink').click(function() {
		$('#overlay').fadeIn(1000);
		$('#modal-container').fadeIn(1000);
		return false;
	});
});
</script>

<style>
#overlay, #modal-container{display:none; } 
#overlay{background:#000; width:100%; height:100%; position:fixed; top:0; left:0;  }
#modal-container{background:#fff; width:820px; height:420px; border:3px #ccc solid; top: 10%; left:50%; margin:0 0 0 -420px; position:fixed;filter:alpha(opacity=100);  opacity:1;}
</style>

Click me to open modal box