jquery4u.com - Archives (juin 2014)

1 jQuery Fan Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets.

Le: 30 06 2014 à 21:00 Auteur: Sam Deering

Instagram is a photo sharing social network with a minimal web-presence and a focus on mobile. Using the service's API, these jQuery plugins bring the sepia-toned network to the web. 1. Pongstagr.am A jQuery plugin that lets you display your Instagram media to your website using Bootstrap Front-end styles and modal-plugin. 2. SpectagramJS An easy-to-use jQuery plugin that uses the Instagram API to fetch and display user information and popular or tagged photo feeds inside your web application or site.

Continue reading %The Best Instagram jQuery Plugins%

Le: 23 06 2014 à 21:00 Auteur: Aurelio De Rosa

We've all used jQuery's animate() to create nice effects on our web pages. Then, with the introduction and the rise of CSS3 they told us that our code was rubbish. They suggested that we dump all of our jQuery-based animations (and in general JavaScript-based animations) in favor of CSS-based ones. This change forced us to deal with a lot of browser (in)compatibility issues and lack of features; not to mention the impossibility to run them on older versions of Internet Explorer. The pain was justified by the fact that CSS animations are faster than JavaScript ones. At least they told us so. It this true? Is jQuery's animate() so slow? Is there a way to enhance it easily without changing our code? The answer is yes. In this article we'll see some of the limitations of both ways of creating animations and then how we can achieve better performance with our jQuery code.

What's the Problem With jQuery?

We all know and love jQuery (actually some people don't). This library, designed to simplify the client side scripting of HTML, has helped hundred of thousands (no real data intended) developers all over the world. It makes things like HTML document traversal and manipulation, event handling, Ajax, and much more a piece of cake, taking the burden to deal with all the browsers' incompatibilities and bugs. Among its features, jQuery also allows to create animations and effects. With it, we can animate CSS properties, hide elements, fade them, and other similar effects. However, jQuery's design goal has never been to be a performant animation engine, and it was never meant to support really complex, cpu/gpu-consuming animations. As a confirmation of this fact, jQuery's memory consumption often triggers garbage collections that cause issues while an animation is performed. In addition, behind the scene jQuery uses setInterval() instead of requestAnimationFrame() (read more about requestAnimationFrame()) to run animations, that doesn't help in producing high frame rates. Due to these factors, people "who know best" evangelized the use of CSS to create our animations and effects.

Continue reading %Easily Improving jQuery Animations%

Le: 18 06 2014 à 21:00 Auteur: Krasimir Tsonev

We use tons of tools every day. Different libraries and frameworks are a part of our daily job. We use them because we don't want to reinvent the wheel for every project, even if we don't understand what's going on under the hood. In this article, we will reveal some of the magical processes happening in the most popular libraries. We'll also see if we can replicate their behaviour.

Creating DOM Elements From a String

With the rise of single page applications, we are doing a lot of things with JavaScript. A big part of our application's logic has been moved to the browser. It is a common task to generate or replace elements on the page. Code similar to what is shown below has become very common.

[js] var text = $('
Simple text
'); $('body').append(text); [/js]

The result is a new <div> element added to the body of the document. This simple operation is done with only one line of jQuery. Without jQuery, the code is a little more complex, but not much:

[js] var stringToDom = function(str) { var temp = document.createElement('div'); temp.innerHTML = str; return temp.childNodes[0]; } var text = stringToDom('
Simple text
'); document.querySelector('body').appendChild(text); [/js]

We defined our own utility method stringToDom that creates a temporary <div> element. We changed its innerHTML property and in the end we simply returned the first child which in practice is what we needed. It worked the same way. However, we will observe different results with the following code:

[js] var tableRow = $('Simple text'); $('body').append(tableRow); var tableRow = stringToDom('Simple text'); document.querySelector('body').appendChild(tableRow); [/js]

Visually, on the page, there are no differences. However, if we check the generated markup with Chrome's developer tools we will get an interesting result:

Creating a DOM element from a string

It looks like our stringToDom function created just a text node and not the actual <tr> tag. But at the same time, jQuery somehow managed to do it. The problem is that the string containing the HTML element is run through a parser in the browser. That parser ignores the tags that are not placed in the right context, and we get only a text node. A table row without a table is not valid for the browser.

jQuery successfully solves the problem by creating the right context and extracts only the needed part. If we dig a bit into the code of the library we will see a map like this one:

[js] var wrapMap = { option: [1, ''], legend: [1, '
', '
'], area: [1, '', ''], param: [1, '', ''], thead: [1, '', '
'], tr: [2, '', '
'], col: [2, '', '
'], td: [3, '', '
'], _default: [1, '
', '
'] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; [/js]

Every element that requires special treatment has an array assigned. The idea is to construct the right DOM element and to depend on the level of nesting to fetch what we need. For example, for the <tr> element we need to create a table with a <tbody> child. So, we have two levels of nesting.

Having a map, we have to find out what kind of tag we want in the end. The following code extracts the tr from <tr><td>Simple text</td></tr>

[js] var match = /<\s*\w.*?>/g.exec(str); var tag = match[0].replace(/</g, '').replace(/>/g, ''); [/js]

The rest is finding the proper context and returning the DOM element. Here is the final variant of the function stringToDom:

[js] var stringToDom = function(str) { var wrapMap = { option: [1, ''], legend: [1, '
', '
'], area: [1, '', ''], param: [1, '', ''], thead: [1, '', '
'], tr: [2, '', '
'], col: [2, '', '
'], td: [3, '', '
'], _default: [1, '
', '
'] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; var element = document.createElement('div'); var match = /< \s*\w.*?>/g.exec(str); if(match != null) { var tag = match[0].replace(//g, ''); var map = wrapMap[tag] || wrapMap._default, element; str = map[1] + str + map[2]; element.innerHTML = str; // Descend through wrappers to the right content var j = map[0]+1; while(j--) { element = element.lastChild; } } else { // if only text is passed element.innerHTML = str; element = element.lastChild; } return element; } [/js]

Notice that we are checking if there is a tag in the string - match != null. If not we simply return a text node. There is still usage of a temporary <div>, but this time we are passing the right tags so the browser can create a valid DOM tree. In the end by using a while loop we are going deeper and deeper till we reach the wanted tag.

Here is a CodePen showing our implementation:

See the Pen xlCgn by Krasimir Tsonev (@krasimir) on CodePen.

Let's continue by exploring the wonderful AngularJS dependency injection.

Revealing AngularJS Dependency Injection

When we start using AngularJS it impresses with its two-way data binding. The second thing which we notice is its magical dependency injection. Here is a simple example:

[js] function TodoCtrl($scope, $http) { $http.get('users/users.json').success(function(data) { $scope.users = data; }); } [/js]

That's a typical AngularJS controller. It performs an HTTP request, fetches data from a JSON file, and passes it to the current scope. We don't execute the TodoCtrl function - we don't have a chance to pass any arguments. The framework does. So, where do these $scope and $http variables came from? It's a super cool feature, that highly resembles black magic. Let's see how it is done.

We have a JavaScript function that displays the users in our system. The same function needs access to a DOM element to put the generated HTML, and an Ajax wrapper to get the data. In order to simplify the example, we will mock-up the data and the HTTP requesting.

[js] var dataMockup = ['John', 'Steve', 'David']; var body = document.querySelector('body'); var ajaxWrapper = { get: function(path, cb) { console.log(path + ' requested'); cb(dataMockup); } } [/js]

We will use the <body> tag as a content holder. ajaxWrapper is the object simulating the request and dataMockup is an array containing our users. Here is the function that we will use:

[js] var displayUsers = function(domEl, ajax) { ajax.get('/api/users', function(users) { var html = ''; for(var i=0; i < users.length; i++) { html += '

' + users[i] + ''; } domEl.innerHTML = html; }); } [/js]

And of course, if we run displayUsers(body, ajaxWrapper) we will see the three names displayed on the page and /api/users requested in our console. We could say that our method has two dependencies - body and ajaxWrapper. So, now the idea is to make the function working without passing arguments, i.e. we have to get the same result by calling just displayUsers(). If we do that with the code so far the result will be:

[js] Uncaught TypeError: Cannot read property 'get' of undefined [/js]

Continue reading %Revealing the Magic of JavaScript%

Le: 17 06 2014 à 21:00 Auteur: Lee Clontz

Build a Better User Registration Page with jQuery

In this Learnable video, you'll learn the basics of jQuery UI by turning a site registration form into a multipart, tabbed interface that works great with mouse, keyboard or touch. You'll learn how to properly format the form's HTML properly for jQuery UI's tabs, how to implement a unified theme for your UI widgets and how to use jQuery buttons to traverse the form as well as some basic validation.

Continue reading %Learnable Screencast: jQuery Forms%

Le: 17 06 2014 à 21:00 Auteur: Lee Clontz

Build a Better User Registration Page with jQuery

In this Learnable video, you'll learn the basics of jQuery UI by turning a site registration form into a multipart, tabbed interface that works great with mouse, keyboard or touch. You'll learn how to properly format the form's HTML properly for jQuery UI's tabs, how to implement a unified theme for your UI widgets and how to use jQuery buttons to traverse the form as well as some basic validation.

Continue reading %Build a Better User Registration Page with jQuery%

Le: 01 06 2014 à 23:00 Auteur: Sam Deering

There are so many jQuery plugins for filtering and sorting, but here are five of my current favorites, which offer a variety of features and effects. 1. Isotope An exquisite jQuery plugin for magical layouts. Enables filtering, sorting, and dynamic layouts. 2. MixItUp A jQuery plugin providing animated filtering and sorting 3. TinySort A small […]

Continue reading %My Top 5 jQuery Filter & Sort Plugins%