G$earch

Building Instagram Photo Search Engine With JQuery And PHP [Tutorial]

Posted by Harshad

Building Instagram Photo Search Engine With JQuery And PHP [Tutorial]


Building Instagram Photo Search Engine With JQuery And PHP [Tutorial]

Posted: 29 Oct 2012 12:02 AM PDT

Ever since Google rolled out instant search features, it has become a popular trend in web design. There are some fun examples online such as Michael Hart’s Google Images app. The techniques are all fairly straightforward where even a web developer with moderate jQuery experience can pick up programming APIs and JSON data.

Live Instant Search Web App for Instagram Photos

For this tutorial I want to explain how we can build a similar instant search web application. Instead of pulling images from Google we can use Instagram which has grown tremendously in just a few short years.

This social network started off as a mobile app for iOS. Users could take photos and share them with their friends, leave comments, and upload to 3rd party networks such as Flickr. The team was recently acquired by Facebook and had published a brand new app for the Android Market. Their userbase has grown tremendously, and now developers can build amazing mini-apps just like this instasearch demo.

Obtaining API Credentials

Before creating any project files we should first look into the ideas behind Instagram’s API system. You will need an account to access the developer’s portal which offers useful instructions for beginners. All we need to query the Instagram database is a “Client ID”.

In the top toolbar click the Manage Clients link, then click the green button “Register a New Client”. You’ll need to give the application a name, short description, and website URL. The URL and Redirect URI can be the same value in this instance only because we don’t need to authenticate any users. Just fill in all the values and generate the new application details.

You’ll see a long string of characters named CLIENT ID. We will need this key later on when building the backend script, so we’ll return to this section. For now we can begin the construction of our jQuery instant search application.

Default Webpage Content

The actual HTML is very slim for the amount of functionality we’re using. Since most of the image data is appended dynamically we only require a few smaller elements inside the page. This code is found inside the index.html file.

<!doctype html>  <html lang="en">  <head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    <title>Instagram Photo Instant Search App with jQuery</title>    <meta name="author" content="Jake Rocheleau">    <link rel="stylesheet" type="text/css" href="style.css">    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>    <script type="text/javascript" src="ajax.js"></script>  </head>    <body>  	<div id="w">  	  <section id="sform">  	    <small>Note: No spaces or punctuation allowed. Searches are limited to one(1) keyword.</small>  	    <input type="text" id="s" name="s" class="sfield" placeholder="Enter a search tag..." autocomplete="off">  	  </section>  		  	  <section id="photos"></section>  	</div>  </body>  </html>  

I’m using the latest jQuery 1.7.2 library along with two external .css and .js resources. The input search field has no outer form wrapper because we don’t want to ever submit the form and cause a page reload. I have disabled a few keystrokes inside the search field so that there are more limited restrictions when users are typing.

We will populate all the photo data inside the middle section ID #photos. It keeps our basic HTML clean and easy to read. All the other internal HTML elements will be added via jQuery, and also removed before each new search.

Pulling from the API

I’d like to start first by creating our dynamic PHP script and then move into jQuery. My new file is named instasearch.php which will contain all the important backend hooks into the API.

<?php  header('Content-type: application/json');    $client = "YOURCLIENTIDHERE";  $query = $_POST['q'];  $api = "https://api.instagram.com/v1/tags/".$query."/media/recent?client_id=".$client;    function get_curl($url) {      if(function_exists('curl_init')) {          $ch = curl_init();          curl_setopt($ch, CURLOPT_URL,$url);          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);          curl_setopt($ch, CURLOPT_HEADER, 0);          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);           $output = curl_exec($ch);          echo curl_error($ch);          curl_close($ch);          return $output;      } else{          return file_get_contents($url);      }  }  

The first line denotes that our return data is formatted as JSON instead of plaintext or HTML. This is necessary for JavaScript functions to read the data properly. Afterwards I’ve got a few variables setup containing the application client ID, user search value, and the final API URL. Make sure you update the $client string value to match your own application.

To access this URL data we need to parse the file contents or use cURL functions. The custom function get_curl() is just a small bit of code which checks against the current PHP configuration.

If you do not have cURL activated this will attempt to activate the feature and pull data via their own functions library. Otherwise we can simply use file_get_contents() which tends to be slower, but still works just as well. Then we can actually pull this data into a variable like so:

$response = get_curl($api);  

Organizing & Returning Data

We could just return this original JSON response from Instagram with all the information loaded up. But there is so much extra data and it’s very annoying to loop through everything. I prefer to organize Ajax responses and pull out exactly which pieces of data we need.

First we can setup a blank array for all the images. Then inside a foreach() loop we’ll pull out the JSON data objects one-by-one. We only need three(3) specific values which are the $src(full-size image URL), $thumb(thumbnail image URL), and $url(unique photo permalink).

$images = array();    if($response){  	foreach(json_decode($response)->data as $item){		          $src = $item->images->standard_resolution->url;          $thumb = $item->images->thumbnail->url;  		$url = $item->link;  		          $images[] = array(          "src" => htmlspecialchars($src),          "thumb" => htmlspecialchars($thumb),          "url" => htmlspecialchars($url)          );        }  }  

Those who are unfamiliar with PHP loops may get lost in the process. Don’t focus so much on these code snippets if you don’t understand the syntax. Our array of images will contain at most 16-20 unique entries of photos pulled from the most recent publication date. Then we can output all this code onto the page as a jQuery Ajax response.

print_r(str_replace('\\/', '/', json_encode($images)));  die();  

But now that we’ve had a look behind the scenes we can jump into frontend scripting. I’ve created a file ajax.js which contains a couple event handlers tied on to the search field. If you’re still following up till now then get excited we’re so close to completion!

jQuery Key Events

When first opening the document ready() event I’m setting up a couple variables. The first two behave as direct target selectors for the search field and photos container. I’m also using a JavaScript timer to pause the search query until 900 millisecond after the user has finished typing.

$(document).ready(function(){    var sfield = $("#s");    var container = $("#photos");    var timer;  

There are only two main function blocks we’re working with. The primary handler is triggered by a .keydown() event when focused on the search field. We first check if the key code matches any of our forbidden keys, and if so negate the key event. Otherwise clear the default timer and wait 900ms before calling instaSearch().

/**    * keycode glossary    * 32 = SPACE   * 188 = COMMA   * 189 = DASH   * 190 = PERIOD   * 191 = BACKSLASH   * 13 = ENTER   * 219 = LEFT BRACKET   * 220 = FORWARD SLASH   * 221 = RIGHT BRACKET   */  $(sfield).keydown(function(e){    if(e.keyCode == '32' || e.keyCode == '188' || e.keyCode == '189' || e.keyCode == '13' || e.keyCode == '190' || e.keyCode == '219' || e.keyCode == '221' || e.keyCode == '191' || e.keyCode == '220') {  	 e.preventDefault();     } else {  		clearTimeout(timer);  	  		timer = setTimeout(function() {  		  instaSearch();  		}, 900);        }  });  

Every time you update the value it’ll automatically go fetch new search results. There are also many of other key codes we could have blocked from triggering the Ajax function – but too many for listing in this tutorial.

The Ajax instaSearch() Function

Inside my new custom function we are first adding a “loading” class onto the search field. This class will update the camera icon for a new loading gif image. We also want to empty any possible data left over within the photos section. The query variable is pulled dynamically from the current value entered in the search field.

function instaSearch() {  	$(sfield).addClass("loading");  	$(container).empty();  	var q = $(sfield).val();  	  	$.ajax({  		type: 'POST',  		url: 'instasearch.php',  		data: "q="+q,  		success: function(data){  			$(sfield).removeClass("loading");  			  			$.each(data, function(i, item) {  				var ncode = '<div class="p"><a rel="external" href="'+data[i].src+'" class="fullsize" target="_blank"><img src="img/full-image.png" alt="fullsize"></a> <a rel="external" href="'+data[i].url+'" target="_blank"><img src="'+data[i].thumb+'"></a></div>';  				$(container).append(ncode);  			});  		},  		error: function(xhr, type, exception) {   			$(sfield).removeClass("loading");  			$(container).html("Error: " + type);   		}  	});  }  

If you’re familiar with the .ajax() function then all these parameters should look familiar. I’m passing the user search parameter “q” as the POST data. Upon success and failure we remove the “loading” class and append any response back into the #photos wrapper.

Within the success function we are looping through the final JSON response to pull out individual div elements. We can accomplish this looping with the $.each() function and targeting our response data array. Otherwise the failure method will directly output any response error message from the Instagram API. And that’s really all there is to it!

Live Instant Search Web App for Instagram Photos

Final Thoughts

The Instagram team has done a wonderful job scaling such a tremendous application. The API can be slow at times, but response data is always properly formatted and very easy to work with. I hope this tutorial can demonstrate that there is a lot of power working off 3rd party applications.

Unfortunately the current Instagram search queries do not allow more than 1 tag at a time. This is limiting to our demo, but it certainly doesn’t remove any of its charm. You should check out the live example above and download a copy of my source code to play around with. Additionally let us know your thoughts in the post discussion area below.

Related posts:

  1. Export and Backup Your Instagram Photos [Quicktip]
  2. Mobile App Design/Dev: Building Navigation with jQuery
  3. How to Browse Instagram Like Pinterest [Quicktip]
  4. 20 Useful Apps to Get the Most Out of Instagram

40 CSS3 Button Tutorials For Designers

Posted: 29 Oct 2012 12:17 AM PDT

In this article, we will go through some hand-picked, awesome tutorials for wonderful buttons you can put on your site using only CSS3.

Some of these buttons play with colors, gradients or shapes while others are programmed to animate with hover or click actions, giving effects like it’s being pushed down; extending, shrinking or switching frames to reveal more information. Anything you can think of to do with buttons, there’s probably an example of it here.

So without further ado, here are 40 Awesome CSS3 button tutorials for web designers. Drop a comment at the end of the article stating your favorite.

Animated Buttons with CSS3 [Demo | Tutorial]

Fancy 3D Button with CSS3 [Demo | Tutorial]

Just Some Awesome CSS3 Buttons [Demo | Tutorial]

CSS3 Social Buttons [Demo | Tutorial]

Pretty CSS3 Buttons [Demo | Tutorial]

Download Me! CSS3 Download Button [Demo | Tutorial]

Add to Cart Button in CSS3 [Demo | Tutorial]

CSS3 Github Buttons [Demo | Tutorial]

CSS3 Animated Bubble Buttons [Demo | Tutorial]

A Set of Simple CSS3 Buttons [Demo | Tutorial]

CSS3 Buttons with Pseudo-Elements [Demo | Tutorial]

Pure CSS3 Social Media Icons [Demo | Tutorial]

Orman Clark’s Chunky 3D CSS3 Buttons [Demo | Tutorial]

Create a Slick CSS3 Button [Demo | Tutorial]

Make Aristo’s Buttons in CSS3 [Demo | Tutorial]

Super Awesome Buttons in CSS3 [Demo | Tutorial]

CSS3 Gradient Buttons with Pattern [Demo | Tutorial]

CSS3 Buttons with Icons [Demo | Tutorial]

Animated CSS3 Buy Now Buttons [Demo | Tutorial]

CSS3 Gradient Buttons [Demo | Tutorial]

BonBon Sweet CSS3 Buttons [Demo | Tutorial]

Create a Multicolour and Size CSS3 Button [Demo | Tutorial]

Multi-Line Buttons with CSS3 [Demo | Tutorial]

How to Make a Cool Pure CSS3 Button [Demo | Tutorial]

Create an Awesome Blue Pill with Icon Button in CSS3 [Demo | Tutorial]

Create a Circle Social Button in CSS3 [Demo | Tutorial]

Create an Awesome Animated CSS3 Download Button [Demo | Tutorial]

Make CSS3 Buttons like a Boss [Demo | Tutorial]

Create Some Awesome CSS3 Buttons [Demo | Tutorial]

How to Create Social Media Icons using CSS3 [Demo | Tutorial]

Slicker Buttons with CSS3 [Demo | Tutorial]

Build Kick-Ass Practical CSS3 Buttons [Demo | Tutorial]

How to Design a Sexy Button using CSS3 [Demo | Tutorial]

Creating CSS3 Buttons in Easy Way [Demo | Tutorial]

Create a CSS3 Circle Button [Demo | Tutorial]

Make CSS3 Buttons that are Extremely Fancy [Demo | Tutorial]

Fading Button Background Images with CSS3 [Demo | Tutorial]

CSS3 Buttons with Glass Edge [Demo | Tutorial]

CSS3 Push-Down Buttons [Demo | Tutorial]

Pure CSS3 Web Button [Demo | Tutorial]

Related posts:

  1. CSS3 Tutorial: Create A Sleek On/Off Button
  2. Gradient in CSS3: Circular and Elliptical
  3. 38 Inspiring CSS3 Animation Demos
  4. Coding Kung-fu: 35 Graphics Built Purely With CSS3

7 Apps To Create Cinemagraphs On Your Smartphone

Posted: 28 Oct 2012 11:59 PM PDT

Previously, we showed you how to create Cinemagraphs, still photos with subtle motions made to suspend your belief or just for fun. Simply put, cinemagraphs create GIF animations with small elements that move while the rest of the picture stays static. They give a pretty awesome effect when done correctly. But having a cinemagraph-making app on your Windows PC gives you a slight disadvantage: you have to transfer your clips into your PC before you can start making your cinemagraphs.

iCinegraph GIF

On the smartphone or tablet however, your videos are already in your gallery and if it’s not good enough, you can just shoot a video clip on the spot before running an app that can help you make a cinemagraph.

Today, we are listing 7 apps to help you create cinemagraphs on your smartphone or tablet. With the help of these apps, the creation of cinemagraphs is simple, fun, and now at your fingertips. Best of all, they all have the share option to help put your cinemagraph on the Internet in no time.

Cinemagraph Apps for iPhone

1. Cinemagr.am

To create cinemagraphs with this free app, start by recording a video with your iPhone. Hold your iPhone steady to get a better end result. It does not matter how long the video is, you just need a small portion of the recording. The small segment you extract from your recording will be used as the static element of the cinemagraph.

Cinemagram App

To create the animation, highlight the area which you want to animate. Next, change the speed of your cinemagraph and choose to play it forward, in reverse or in a forward-and-reverse loop.

You can then preview your cinemagraph and add filters. Once that’s done, you can post it on the app itself, or on your favorite social networking site (Twitter, Facebook, Tumblr). The app also supports hashtags and geotags.

Cinemagram GIF

Using Cinemagr.am is very much like Instagram; you have your own profile where friends can follow your uploads and like or comment on it – even the navigational buttons have similar functions. You also can ‘repost’ what other users have uploaded. [Free]

2. Flixel

Most of these cinemagraph-making apps require you to have a steady hand while recording; to address this shakiness, this app, Flixel wil let you know if your video is too shaky while processing your recording. You get only 4 seconds of recording time, which once processed can be trimmed, have filters added to it or looped.

Flixel App

From here, there are 2 routes that you can take: either save it as a fully animated clip or create a cinemagraph by tapping the ‘Cinemagraph it’ button. When tapping that button, you highlight the area which you want animated. Once that is finished, your cinemagraph is ready and you can now share it.

Flixel GIF

There is a number of sharing options to choose from: Twitter, Facebook, Tumblr or by email. You can also save it without sharing, keeping the cinemagraph private for your own viewing pleasure, or save it as an MP4 or GIF file on your iPhone’s Camera Roll. [Free]

3. Echograph

There are three steps to creating a cinemagraph with Echograph. The first is to trim the duration of the video; it allows your clip to be 5 seconds or less. You do this by adjusting the front and back sliders of the playback bar. In this step, you can also reverse or add a pause to the end of your clip to compliment the effect you’re trying to achieve.

Echograph App

Secondly, choose your still frame (the static backdrop) of your cinemagraph. You can choose this still frame from any point of your original video by using the slider on the playback bar. Lastly, highlight the areas that you want to animate. As you can imagine, the combination of the still frame in step two and animated area of step three will give you a cinemagraph.

Echograph GIF

Then you can save it as a low- or high-definition cinemagraph and share it on Facebook, Twitter, Tumblr or by email. You can also share it with the Echograph team for a chance to be listed as a ‘Staff Pick’ on their website. [$1.99]

4. Kinotopic

Creating cinemagraphs or ‘Kinos’ is quite simple. You start out by recording a 3 second long video or trim a video from your camera library. Then, add filters and highlight the area you want to animate – so far it’s a typical cinemagraph app.

Kinotopic App

What’s unique about this app is that under ‘Settings’, you can stabilize your clip. This feature is similar to what is found in the Windows program Cliplets. If you have a slightly shaky clip, you can use this to better enhance the effect of your cinemagraph. Once you’ve completed creating your cinemagraph, you can share it on Facebook, Twitter or Tumblr.

Kinotopic GIF

There are two versions of the app: the paid version allows you to save high-quality cinemagraphs and allows you to use it without registering through email or your Facebook account. Another unique feature is that Kinotopic will set you up with your own profile page which can be accessed at kinotopic.com/username. [Free]

5. iCinegraph

Start making your cinemagraph by picking a video from your camera library or recording a new clip. When recording a new clip, a timer is shown to show you the duration of your recording. What’s unique about this app is that the recording duration is not limited to just a few seconds.

In the next step, you’ll pick a keyframe which will be used as the static backdrop of your cinemagraph. This app gives you a box to outline the area you want animated instead of a highlight option.

iCinegraph App

You can box out a small area to create a cinemagraph or cover the entire canvas to create an animated gif. Once you’re done, you can preview and save your cinemagraph. Depending on how long your video clip is, this can take some time to process.

iCinegraph GIF

You can save the cinemagraph on your iPhone Camera Roll and email it to your friends. Since you cannot view a cinemagraph from the iPhone photo library, iCinegraph comes with a Viewer that allows you to view all cinemagraphs on your iPhone. [Free]

Cinemagraph Apps for Android

1. Fotodanz

Once Fotodanz is launched, you’ll be at the capture screen where you tap the button at the bottom to begin recording. You can record for a duration of 3 or 5 seconds and it’ll automatically stop. Unlike previous apps, instead of highlighting an area, you’ll have to draw a circle around the area you want animated.

Fotodanz App

In the next step, you’ll be able to preview your cinemagraphs and return to the previous step to refine it if necessary. You can then select a number of filters to use with your cinemagraph. Once you’ve saved it, you’ll be taken to your photo album where you can share it through email.

Fotodanz GIF

At the moment there is no direct social network sharing option to Facebook, Twitter, Tumblr or Google+ yet, but they’re developing future updates on the app to include that. [Free]

Pictoreo

Pictoreo requires a registered profile before you can start using the app. You’re only allowed 3.5 seconds of recording time and you highlight what you want to animate. You’ll then get a instant preview of what the cinemagraph would look like and you can refine it with the eraser.

Pictoreo App

Name your cinemagraph and share it on Facebook, Twitter or the Pictoreo network. Note that the final outcome is not a GIF format but an MP4 video file that gives the same format. There is also the option to geotag your cinemagraphs. [Free]

Pictoreo GIF

So start making your cinemagraphs now or share with us your favorite cinemagraph-making app in the comments.

Related posts:

  1. Create Cinemagraphs Easily Using Cliplets
  2. 20 Best iPhone Spy Apps
  3. 30 iPhone & iPad Apps to Have Fun with Your Photos
  4. 15 Android Apps Every Blogger Should Have

A Look Into: Scalable Vector Graphics (SVG) Animation

Posted: 28 Oct 2012 11:56 PM PDT

Today we are going to continue our discussion on Scalable Vector Graphic (SVG), and this time we are going to work with SVG Animation. Don’t be scared though, SVG Animation is relatively easy and actually in this post we will start from the basics.

Basic Implementation

Animation in SVG can be done through <animate> element;

  <svg>  <rect width="200" height="200" fill="slategrey">  <animate attributeName="height" from="0" to="200" dur="3s"/>  </rect>  </svg>  

As you can see from the code snippet above, we add the <animate> inside the element that is going to affected. This <animate> contains some of the following attributes;

attributeName: This attribute specifies which element’s attribute will be affected in the animation.

from: This attribute is optional, we can specify an exact value or leave it to let it start from where it was.

to: This attribute specifies the animation direction. Depending on the specified value in attributeName, the results may vary. But in this example it will extend the height.

dur: This attribute specifies the animation duration. The value of this attribute is expressed in Clock Value Syntax. For example, 02:33 represents 2 minutes and 33 seconds, while 3h is equal to 3 hours, but we don’t need that long so we specified the duration for just 3s or 3 seconds;

The same thing goes to <circle> element, but this time we target the circle’s radius attribute (r).

  <svg>  <circle r="100" cx="100" cy="100" fill="slategrey">  <animate attributeName="r" from="0" to="100" dur="3s"/>  </circle>  </svg>  

Moving Element

In moving SVG elements, we only need to target the element’s coordinate x and y;

  <svg>  <rect x="0" y="0" width="200" height="200" fill="slategrey">  <animate attributeName="x" from="0" to="200" dur="3s" fill="freeze"/>  </rect>  </svg>  

In the example above, we move the rectangle from 0 to 200 in 3 seconds, the rectangle will appear moving horizontally from the left to the right. Also, if you look carefully we also added another attribute to the <animate> element, namely fill.

fill attribute here is nothing to do with the background color like in the other SVG elements. This attribute specifies how the animation will act after the duration ends. In this example we freeze the affected element so it stays where the animation ends.

It also works similarly to the <circle> element, we can use cx or cy, like so:

  <svg>  <circle r="100" cx="100" cy="100" fill="slategrey">  <animate attributeName="cy" from="100" to="200" dur="3s" fill="freeze"/>  </circle>  </svg>  

Animate Multiple Attributes

So far, we only target one attribute to be animated, but it is also possible to animate more than one attribute at once. The example below shows how we do it:

  <svg>  <circle r="100" cx="110" cy="110" fill="slategrey" stroke="#000" stroke-width="7">  <animate attributeName="r" from="0" to="100" dur="3s"/>  <animate attributeName="stroke-width" from="0" to="10" dur="7s"/>  </circle>  </svg>  

As you can see, it works in a similar way, only now we have two <animate> elements inside the <circle> to target the radius and the stroke width to be affected.

Following a Path

In our previous post on Working with Text in SVG, we have showed you how to flow the Text to a Path. It is also possible to do the same thing in SVG Animation, we can animate an element to follow a Path. Here is an example.

  <svg>    <defs>  <path id="thepath" fill="none" stroke="#000000" d="M0.905,0.643c0,0,51.428,73.809,79.047,166.19s68.095,38.572,107.144-18.095  c39.047-56.667,72.381-92.382,113.333-42.381S335.5,178.5,374,200.5s82-18.5,97.5-33.5"/>  </defs>    <circle r="15" cx="15" cy="15" fill="slategrey">    </svg>  

The Path is better defined within a <defs> element, like shown above. In order for the element to follow the Path, we need to define the animation with <animateMotion> and link the path id with <mpath> element, as follows;

  <animateMotion dur="3s">  	<mpath xlink:href="#thepath"/>  </animateMotion>  

That’s it, now let’s see it in action;

Transformations

We can also use transformation like scale, translate and rotate for the Animation, and to do so we will use <animateTransform>;

  <svg>  <rect width="200" height="200" fill="slategrey">  <animateTransform attributeName="transform" type="scale" from="0" to="1" dur="3s"/>  </rect>  </svg>  

Transformations in SVG shares similar principles with CSS3, and we have covered about it quite comprehensively in our previous post about CSS3 2D Transformation.

Final Thoughts

Depending on your proficiency on SVG Animation you can create something like this or maybe this one.

One advantage of using SVG Animation over Flash Animation is that it doesn’t rely on third-party plugins to work and it also considerably faster than Flash. After Adobe stopped their Flash support in Android, you might want to start trying out this approach to serve animation in your next website.

Further References

Related posts:

  1. Styling Scalable Vector Graphic (SVG) with CSS
  2. A Look into: Scalable Vector Graphics (SVG)
  3. Working with Text in Scalable Vector Graphics (SVG)
  4. Creating Advanced “Marquee” with CSS3 Animation

0 comments:

Post a Comment