jquery Draggable plugin

Lightweight Draggable() jQuery plugin

A  simple lightweight jQuery plugin that adds cross-browser dragging support.

(jquery draggable plugin)

Supports Axis restriction, Parent Boundary restriction.

Demonstration: http://jsfiddle.net/yelton/2TQgB/

Download on Github: https://github.com/scazzy/jQuery-Draggable

If your application requires dragging of elements, creating scrollbars, or anything that can make your app look sexy sticky and dragging, here’s the thing for you.

Unlike Jquery UI’s draggable plugin, that is heavy for your application, (and that requires you to download the pre-requisites to use just the dragging functionality, this one is lightweight (just 1.1Kb minified).

In order to use the plugin, simply bind the “draggable” event to an element.

Here is an example:

<br /><br />// Basic dragging a div<br />$("div").draggable();<br />
&lt;/pre&gt;<br />// Restricting dragging to an axis<br />$("div").draggable({<br /><%%KEEPWHITESPACE%%>  axis: 'x'<br />});<br />
&lt;/pre&gt;<br />// Restricting dragging to it's parent container (boundary)<br />$("div").draggable({<br /><%%KEEPWHITESPACE%%>  containParent: true<br />});<br />

Displaying all your Instagram images, ignoring next page and pagination

Sometimes you’d like to know exactly how many images a given Instagram account has since creation. This unfortunately is not an option with the current API and today I’ll discuss a work around.

Here’s an example of an Instagram response, note the “next_url” object.

[pagination] => stdClass Object
        (
            [next_max_tag_id] => 1335219704338
            [deprecation_warning] => next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead
            [next_max_id] => 1335219704338
            [next_min_id] => 1335219773953
            [min_tag_id] => 1335219773953
            [next_url] => https://api.instagram.com/v1/tags/fun/media/recent?access_token=20576411.a30aaf6.c50198ecb09747788f0310e2c49964ed&min_id=&max_id=&max_tag_id=1335219704338
        )

    [meta] => stdClass Object
        (
             => 200
        )

    [data] => Array
        (
            [0] => stdClass Object

As you can see in the above example, The pagination object contains "next_url" which is a link to the next set of pictures. So what if you don't want a link to the next set but you want one big, bulk response of all the pictures? Where create an array of responses of course!

function __apiCall($url, $post_parameters = FALSE) {

    	// Initialize the cURL session
	    $curl_session = curl_init();

	    // Set the URL of api call
		curl_setopt($curl_session, CURLOPT_URL, $url);

		// If there are post fields add them to the call
		if($post_parameters !== FALSE) {
			curl_setopt ($curl_session, CURLOPT_POSTFIELDS, $post_parameters);
		}

		// Return the curl results to a variable
	    curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);

	    // Execute the cURL session
	    $contents = curl_exec ($curl_session);

		// Close cURL session
		curl_close ($curl_session);

		// Return the response
		return  json_decode($contents);
    }

As you can see in the above snippet (reading the comments) we take the set of parameters, use curl to send them to the endpoint, receive and decode our response and return it. Simple. What we need to do is leverage this function, with another function that will keep looping as long as it finds a "next_url" object in the currently received JSON response.

function getResults($url){

        $gotAllResults = false;
        $results = array();

        while(!$gotAllResults) {
        $result = $this-&gt;__apiCall($url);
        $results[] = $result;

        if (!property_exists($result-&gt;pagination, 'next_url')) {
            $gotAllResults = true;
        } else {
            $url = $result-&gt;pagination-&gt;next_url;
        }
    }

    return $results;

    }

And there you have it. The function above takes the url (endpoint for the API), defines the $results variable as an empty array that we will add to for each page and the $gotAllResults variable, which will be set to TRUE once there are no more pages(or "next_url" objects). Our while statement first tests that $gotAllResults is FALSE then performs the _apiCall function seen further above, receives the response and adds it to the array. The if state checks the current response to see if the "next_url" object exists, if it no longer does(meaning we have reached the end of the responses) it will set $gotAllResponses to TRUE, cancel out the while statement and return our array of results.

Now that we have our big array of JSON responses, parsing it can be tricky. Below is a snippet similar to what I uses to parse and display my API call, showing the image and some information about it...

Understanding the Push – Forever-frame/polling/comet

Understanding the Push for Web

You must have heard of Push technology being used in the tech industry since a long time. And with the web being a trend, and an enourmous amount of userbase accessing websites, how do you keep the data realtime without effecting much of your network and database resource.
Push technology is one of the solutions in such cases. Push technology is not really a form of any specific tech, but a concept.
Example: Facebook live notifications or Gmail incoming mail notifications
You must have thought sometime of how do you get the notification ticks so quickly as soon as your friend pokes or likes your post.
One solution is, firing a “check my notifications” every few second of interval. That might just work good in your application, if it’s small enough or you have good cash for the server/network headaches.
The other better solution here uses comets / forever frame / polling.

Well, the forever frame technique is quite old, but just what you might need in your next app.
A common method of doing such notifications is to poll a script on the server (using ajax) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened

A common method of doing such notifications is to poll a script on the server (using ajax) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened.

The way facebook does it is using the comet approach, rather than polling on an interval, as soon as one poll completes, it issues another one. However, each request to the script on the server has an extremely long timeout, and the server only responds to the request once something has happened. You can see this happening if you bring up Firebug’s Console tab while on facebook, with requests to a script possibly taking minutes. It is quite ingenious really, since this method cuts down immediately on both the number of requests, and how often you have to send them. You effectively now have an event framework that allows the server to ‘fire’ events.

Behind this, in terms of the actual content returned from those polls, it’s a JSON response, with what appears to be a list of events, and info about them. It’s minified though, so is a bit hard to read.

In terms of the actual technology, ajax is the way to go here, because you can control request timeouts, and many other things. I’d reccommend (Stack overflow cliche here) using jQuery to do the ajax, it’ll take a lot of the cross-compability problems away. In terms of php, you could simply poll an event log database table in your php script, and only return to the client when something happens? There are, I expect, many ways of implementing this.

Implementing:

Server Side:

There appear to be a few implementations of comet libraries in php, but to be honest, it really is very simple, something perhaps like the following pseudocode:

while(!has_event_happened()) {
   sleep(5);
}

echo json_encode(get_events());
  • The has_event_happened function would just check if anything had happened in an events table or something, and then the get_events function would return a list of the new rows in the table? Depends on the context of the problem really.
  • Don’t forget to change your php max execution time, otherwise it will timeout early!

Client Side:

Take a look at the jQuery plugin for doing Comet interaction:

That said, the plugin seems to add a fair bit of complexity, it really is very simple on the client, perhaps (with jquery) something like:

function doPoll() {
   $.get("events.php", {}, function(result) {
      $.each(result.events, function(event) { //iterate over the events
          //do something with your event
      });
      doPoll();
      //this effectively causes the poll to run again as
      //soon as the response comes back
   }, 'json');
}

$(document).ready(function() {
    $.ajaxSetup({
       timeout: 1000*60//set a global ajax timeout of a minute
    });
    doPoll(); // do the first poll
});

The whole thing depends a lot on how your existing architecture is put together.

THE PERFECT PHP CLEAN URL GENERATOR (I have found)

In my hunt for the perfect clean url (smart url, slug, permalink, whatever) generator I’ve always slipped in some exception or bug that made the function a piece of junk. But I recently found an easy solution I hope I could call “definitive”.

Clean url generators are crucial for search engine optimization or just to tidy up the site navigation. They are even more important if you work with international characters, accented vowels /à, è, ì, .../, cedilla /ç/, dieresis /ë/, tilde /ñ/ and so on.

First of all we need to strip all special characters and punctuation away. This is easily accomplished with something like:

function toAscii($str) {
	$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $str);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_|+ -]+/", '-', $clean);

	return $clean;
}

With our toAscii function we can convert a string like “Hi! I’m the title of your page!” to hi-im-the-title-of-your-page. This is nice, but what happens with a title like “A piñata is a paper container filled with candy”?

The result will be a-piata-is-a-paper-container-filled-with-candy, which is not cool. We need to convert all special characters to the closest ascii character equivalent.

There are many ways to do this, maybe the easiest is by using iconv.

setlocale(LC_ALL, 'en_US.UTF8');
function toAscii($str) {
	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$clean = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $clean);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_| -]+/", '-', $clean);

	return $clean;
}

I always work with UTF-8 but you can obviously use any character encoding recognized by your system. Thepiñata text is now transliterated into a-pinata-is-a-paper-container-filled-with-candy. Lovable.

If they are not Spanish, users will hardly search your site for the word piñata, they will most likely search forpinata. So you may want to store both versions in your database. You may have a title field with the actual displayed text and a slug field containing its ascii version counterpart.

We can add a delimiter parameter to our function so we can use it to generate both clean urls and slugs (in newspaper editing, a slug is a short name given to an article that is in production, source).

setlocale(LC_ALL, 'en_US.UTF8');
function toAscii($str, $delimiter='-') {
	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

	return $clean;
}

// echo toAscii(“A piñata is a paper container filled with candy.”, ‘ ‘);
// returns: a pinata is a paper container filled with candy

There’s one more thing. The string “I’ll be back!” is converted to ill-be-back. This may or may not be an issue depending on your application. If you use the function to generate a searchable slug for example, looking for “ill” would return the famous Terminator quote that probably isn’t what you wanted.

setlocale(LC_ALL, 'en_US.UTF8');
function toAscii($str, $replace=array(), $delimiter='-') {
	if( !empty($replace) ) {
		$str = str_replace((array)$replace, ' ', $str);
	}

	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

	return $clean;
}

You can now pass custom delimiters to the function. Calling toAscii("I'll be back!", "'") you’ll get i-ll-be-back. Also note that the apostrophe is replaced before the string is converted to ascii as character encoding conversion may lead to weird results, for example é is converted to 'e, so the apostrophe needs to be parsed before the string is mangled by iconv.

The function seems now complete. Lets stress test it.

echo toAscii("Mess'd up --text-- just (to) stress /test/ ?our! `little` \\clean\\ url fun.ction!?-->");

returns: messd-up-text-just-to-stress-test-our-little-clean-url-function

echo toAscii("Perché l'erba è verde?", "'"); // Italian

returns: perche-l-erba-e-verde

echo toAscii("Peux-tu m'aider s'il te plaît?", "'"); // French

returns: peux-tu-m-aider-s-il-te-plait

echo toAscii("Tänk efter nu – förr'n vi föser dig bort"); // Swedish

returns: tank-efter-nu-forrn-vi-foser-dig-bort

echo toAscii("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ");

returns: aaaaaaaeceeeeiiiidnooooouuuuyssaaaaaaaeceeeeiiiidnooooouuuuyy

echo toAscii("Custom`delimiter*example", array('*', '`'));

returns: custom-delimiter-example


echo toAscii("My+Last_Crazy|delimiter/example", '', ' ');

returns: my last crazy delimiter example

I’m sure we are far from perfection and probably some php/regex guru will soon bury me under my ignorance suggesting an über-simple alternative to my function. What do you thing?

Post source author: Andre, from Cubiq.org

JSON tools & utilities

When you are playing with json data for your next php/js application, you might get frustated over analyzing the json data before parsing or rendering. Or at other times while using third-party apis, like youtube, twitter or instagram, the data may be so large to dive in and understand the nodes or levels.

There are some utility web tools that might help you ‘beautify’ the mess of json data and display it to you in a clean layout.

1. http://jsonviewer.stack.hu/
Its a simple json beautifier that displaus the data in a simple tree structure.

2. http://jsonmate.com
Json mate is pretty because it gives you a more beautiful layout of your data, and even helps you compress your large json data.

3. http://codebeautify.org/view/jsonviewer
C
ode Beautify

3. Not new, but firefox’s popular plugin ‘fire-php’ also allows you to see a structured version of your json data, or any other array.

Beginner Resources to HTML5, JavaScript, jQuery, Backbone, and CSS3

A BEGINNER’S JOURNEY

HTML5

So, it is pretty obvious that you are going to need to learn HTML5 if you are doing to do front-end web development. From my experience most developers regardless of their language of choice know the basics of HTML. What they may or may not know are all the newer semantic tags, cross-browser tricks, and native JavaScript APIs.

There is plenty to learn in HTML5 without getting into the JavaScript APIs just yet. Once you learn JavaScript and feel comfortable in it, that may be the best time to tackle topics such as Geolocation, Web Sockets, Canvas, IndexDB, Web Workers, etc…

Resources

JAVASCRIPT

Even if you think you know JavaScript it might behoove you to go back and learn it from the beginning. A common danger is that developers think it looks just like their back-end language of choice (C, C++, C#, or Java) that they don’t invest time to learn how it is different.

JavaScript is a dynamic and functional language, which is considerably different than C# or Java for example. So, please take your time and pick up the language. If you don’t learn it appropriately you will invariably run into barriers down the road due to lack of understanding.

Resources

JQUERY

The jQuery library has been around for several years and has catapulted as one of the most used tools in the web developer’s belt. The reason for its vast usage is that it solves many of the cross-browser issues that creep up during development. The library is popular for both web developers and web designers. The community around jQuery is amazing and there are tons of jQuery plugins to choose from.

Resources

BACKBONE.JS

If you find yourself writing more and more JavaScript and jQuery then you may want to consider picking up Backbone.js to help you organize your web application. This library is also a great fit for Single Page Applications (SPA). Backbone.js uses the familiar MVC/MVP concepts of Models, Collections, Views, and Routers. In addition there is a nice Event model, History support, and a Sync mechanism. The community for Backbone.js is also very large and you can find many extensions and plugins to fit your needs.

Resources

CSS3

You may or may not have experience with CSS. Brushing up on CSS concepts would be a good thing. If you already feed proficient at CSS1-2, then you should pick up CSS3 as well. A lot of features have been added recently that is in most modern browsers. There are many things that you can do in CSS3 now where you used to use JavaScript or custom images.

Resources

FEATURE DETECTION

Inevitably you’ll need to support browsers that don’t support the native feature you are trying to use. Thankfully you can use Feature Detection to determine if the browser you are in implements that feature and if it doesn’t then you can provide functionality to mimic that feature (a.k.a. a polyfill or shim).

Resources

RESPONSIVE WEB DESIGN

Instead of implementing a different UI for mobile devices, tablets, and desktop browsers you can use responsive web design techniques to provide one experience that restructures the UI according to its size.

Resources

CONCLUSION

Hopefully the above resources will get you started in your transition to front-end web development. There is a lot to learn, but it is an exciting space that changes frequently. Having a desire to learn is a good trait to have in this field.

If you have any resources that you think I missed please add them in the comments and I’ll try to update the lists above if I think they are appropriate.