In this post I will show you how to parse a text file containing shortcodes with jQuery. The technique detailed here, which makes use of the
$.ajax()
method and regular expressions, can be applied to INI files as well.
Archive for August 2011
CSS: animating form elements
With the brand new CSS3 transitions we can create interesting animations on form elements. For example, we can outline a text input by increasing its size and changing its background and border color when it gets the focus state. Let's see how.
jQuery: image division, explosion and the like
Dividing an image with jQuery simply means that you have to create several elements which contain a different part of the image set as their background image and shown via the
background-position
property. So here's a simple (simple indeed!) plugin which, given the number of parts, their dimensions, the animation speed and an array of background coordinates, divides an image.
jQuery: loading tables faster
Writing high performance jQuery code is a task that requires some basic knowledge of how jQuery's methods work internally. For example, the
html()
method uses the clean()
method to preprocess the HTML string passed in as argument. This makes html()
much slower than the traditional innerHTML
property. When it comes to tables, tests have shown significant improvements in slower browsers when HTML tables are built as arrays of strings which are turned into a plain HTML string using the join()
method. Let's see how.
jQuery: debugging elements in the console
When we create complex DOM structures with jQuery, it's vital to keep track of the inner structure of each element. We can actually log such structures to the console in order to analyze how the DOM has been constructed. To accomplish this task, we need to gather as much information as possible about our elements. Let's see how.
jQuery: video trailer for YouTube
I've just created a demo that shows a nice implementation of a video trailer for our YouTube videos. My demo makes use of jQuery and jQuery UI effects to create a simple presentation of a video. The source code, in its essence, is made up of chained animations glued together by the callback functions of each animation. Feel free to use this demo in your own projects. Of course mentioning me would be surely appreciated. Enjoy!
jQuery: create a Twitter tweet button
Twitter provides a useful guide to create and customize our tweet buttons. In this post, I'll show you how to implement a basic Twitter tweet button with jQuery. Let's get to work.
Accessibility: using social networks with Lynx
The following video shows my attempts to use the mobile versions of Facebook and Twitter with Lynx, the textual browser. Facebook fails, while Twitter successfully logs me in and lets me publish a tweet. I hope you find it useful.
CSS: using @font-face
A couple of minutes ago I inserted the DejaVu Serif font on a Wordpress web site I'm working on. The main style sheet which makes use of the
@font-face
rule was downloaded from Font Squirrel together with the source fonts. There are four web fonts formats available: TTF, EOT, SVG and WOFF. At a first glance, the @font-face
rule has been used several times to include all font variants. Each rule block takes care of inserting the specified variant using the four available formats. Let's take a look at these rules.
jQuery: JSDoc and plugin development
There's a widespread trend in jQuery's coding that gets developers accustomed to the bad practice of not following a common comment standard while developing plugins. A well-commented plugin is more useful than a plugin where comments are simply put in the code without any discernible order or meaning. That's where JSDoc comes into play.
jQuery: Twitter ticker
The secret of jQuery's Twitter tickers is simple: if you want to safely execute the rotation, timers and the like, put all your routines within the
$.getJSON()
scope. Otherwise, it won't work. Said that, let's get to work.
jQuery: the $.getScript() method
The jQuery's $.getScript() method is an AJAX method that allows us to load a JavaScript file and execute it in the global context. The peculiarity of this method is that it doesn't execute scripts which contain syntactic errors. However, if a script contains errors, nothing will be shown in your JavaScript console. For that reason, it's recommended to set up an error handler using the
ajaxError
event. Let's see how.
jQuery: difference between position() and offset()
The difference between the jQuery's
position()
and offset()
methods concerns the way by which the top
and left
coordinates are calculated. The former always refers to the parent element's coordinates, while the latter may calculate such coordinates by taking into account the offset of the parent from the whole page when this element is positioned. If the parent element is not positioned, that is, if its CSS position is static
, then both methods return the same results. Let' see an example.
jQuery: image organizer
The following demo shows a very simple implementation of an image organizer with jQuery. I focused on essential features mostly. For that reason, I recommend you to study the source in order to write your own version, possibly AJAX-enabled. In the meantime, enjoy this demo!
jQuery: draggable objects details
In this post I'd like to make it clear to myself and you, dear reader, what happens behind the scenes of jQuery's draggable objects. jQuery UI is a great tool, but sometimes it's difficult to tame our scripts if we don't know all the details. Draggable objects fall into such category. Setting up a demo page to mimic the basic behavior of the widget section of Wordpress is not that easy because when we start coding we can't know all the nuts and bolts of dragging objects around the screen and from an element to another. Let's see these details.
jQuery: generate a random password
The word "random" should not be taken literally when it comes to JavaScript. However, in the following example I've tried to reproduce the basic routine of many similar PHP functions, though the final result doesn't take into account the removal of character duplicates. So I've created a basic jQuery global function to perform this task. Let's see how.
jQuery: tracking, inspecting and debugging animations
Keeping track of the changes made to CSS properties during animations and inspecting their state it's a useful feature, especially for debugging. For that reason, I've created a simple tracking plugin that uses an array of CSS properties to follow the state of animation step by step. This simple plugin also stores the
selector
and context
properties of the current jQuery's object to help you to locate the animated element in the DOM. Let's see the details.
CSS: 5 tips for a better typography
CSS typography has always been misused or misunderstood in some way. It's not about text properties or accessibility only, but also about design and beauty. It's time to try to get back the pure visual effects of a good typography. So here are five simple tips for a better CSS typography.
jQuery: LavaLamp image gallery
The LavaLamp effect can also be applied to an image gallery, thus creating the effect of a dynamic frame that follows the mouse on the images. The implementation is almost identical to a single menu with a LavaLamp effect attached to it. Let's see the details.
CSS: animating a navigation menu
The concept of CSS transition applies only to particular states of an element. A CSS transition is much like an event listener: it keeps track of the properties of an element and when such properties change during a state, it simply applies an effect to the affected properties. States, for example, are
:hover
and :focus
. Transitions work this way: you have to register a transition on the normal state of an element and then change some properties on a different state of the element (e.g. :hover
). In this post I'll show you how to animate a navigation menu using transitions.
jQuery: custom events
The jQuery's
bind()
method allows us to define our custom events as simple but powerful inline functions. A custom event has a name (specified between quotes) and a callback function that defines its behavior. Custom events can be invoked using the trigger()
method. Let's see an example.
HTML5: semantics of header and footer and their difference
header
and footer
are two HTML5 elements which too often are considered only from the presentational point of view. In this post, I'd like to emphasize their semantic role in the overall structure of an HTML5 document.
CSS: zooming images
Today I've found a nice jQuery demo which creates a zoom effect on images using the
hover
event. This is something that can be actually done with CSS. So here's my demo.
HTML5: difference between section and article
HTML5 introduces two new elements that pose some semantical problems concerning their use:
article
and section
. Most web developers get confused by these new elements. Generally speaking, the semantics of these elements is not well-defined in the HTML5 specifications. Let's try to make things clearer.
CSS: the nth-child selector in action
The
nth-child
structural pseudo-class is a powerful CSS3 selector that allows us to select elements based on their position in the DOM. Such position is a numerical index starting from 1. In this post I'll show you how this selector can be used to style elements in a more dynamic and flexible way.
PHP: converting RSS to JSON
Converting RSS to JSON requires only a sufficient knowledge of the
json_encode()
function and one of the XML libraries and extensions that come shipped together with PHP. In this post I'll show you a basic routine to convert an RSS feed to a JSON file using the PHP's DOM extension.
jQuery: testing remote JSON data with a type check
The
$.getJSON()
method of jQuery provides an easy way to retrieve a JSON resource to be used in your documents. Unfortunately, this method doesn't provide an option to test whether the returned data has been fetched normally and is ready to be used. Instead of using $.ajax()
as an alternative, you can enhance this method with a simple check on data to verify the correct parsing of the resource. Let's see how to implement this enhancement.
PHP: creating your own JSON API
The following video shows how to create and implement your own public API using JSON as the default data exchange format. The core of your API will be made up by PHP. This is a really useful tutorial.
Google: frequency of site updates and indexing
If you don't update your site regularly, your indexing by SE will be affected in a significant way. Google adjusts the frequency of the spider's visits based on the times you publish new contents on your site. This blog has been affected by a fluctuation in its update frequency and Google did react accordingly. Before the fluctuation, Google indexed my site contents as soon as a new post was published. Currently, it indexes my contents only after 24/32 hours. I don't know if there was also a reassessment by the end of the month that also affected the indexing routine, but I know for sure that now such indexing shows significant delays.
jQuery: using animation steps
Each jQuery animation can be broken down into singular atoms called steps. A step is a fragment of an animation and it allows jQuery to handle all of its effects on elements. Without steps, animations will be always instantaneous and without any possible additional effect, such as delay, easing and so on. jQuery allows us to control such steps using the
step()
method of the animate()
method. Let's see the details.
jQuery: image gallery with zoom
We have an image gallery with thumbnails. You click on a thumbnail and a magnifying glass appear, while the thumbnail itself becomes semitransparent. You click on the magnifying glass and the full-sized image appear with a fade in effect. This is a simple effect to achieve with jQuery. Let's dig into the gory details.
jQuery: inspecting objects and create a reflection API
jQuery already provides some reflection-like structures to gather information about some JavaScript components. However, we can use the extensibility of the library to get metadata from objects or, if you prefer, classes. More specifically, we want to know if a given member of an object is a property, a method or another object.
jQuery: handling payment calculations in a shopping cart
Usually all payment calculations in a shopping cart are handled by a server-side language which fills out an HTML table with all the required numbers. For example, you have a table with some text inputs that allow the user to modify the quantity of his products. With jQuery, you can easily perform all these calculations (subtotal for example) without refreshing the page. Let's see how.
jQuery: removing duplicates from a list
Removing duplicated content from a list is quite a complex task if we don't know that all jQuery's methods for working with arrays simply deal with DOM nodes and not with their content. For that reason, we have to create an helper method to allow us to remove duplicated items from an an array. Let's see the details.
jQuery: create elements the right way
jQuery is full of surprises. The
$()
wrapper, in particular, is more flexible than one could expect. When we create elements on the fly, this wrapper accepts an object literal as its second argument where we can specify attributes and content of the newly created element. This is a really useful feature when we want to write a more concise and compact code. Let's see the details.
JavaScript: avoid lookups and optimize performance
Caching objects and references is a good coding practice to avoid lookups in browsers. Generally speaking, most modern browsers have significantly improved their lookups routines but not all. More specifically, IE8 and lower have still significant problems with lookups and performance. So if you want to get good results with performance, start caching!
Wordpress: integrating Flickr with jQuery
Integrating Flickr in Wordpress is an easy task with jQuery. All we need is a Text widget where we can put an HTML element and a simple jQuery function. Let's see the details.
jQuery: detecting HTML5
Sometimes your code needs that the host document uses HTML5. How can you detect if your target document is using HTML5? There are currently two ways of doing this: DTD detection and element detection. Let's see the analysis of both approaches.
Pure CSS3 pullquote
In this post I'll show you how to create a pullquote with the latest features of CSS3, namely gradients, rounded corners, box shadows and transformations. We'll also use generated content and we're going to rotate it. The final effect is surely very impressive from a visual point of view. Let's get to the details.
CSS testing guidelines
Ian Hickson wrote a poignant and seminal article on writing test cases for web browsers. Though its depth and accuracy, this article is not very useful when it comes to CSS testing. Since I have already made some tests (also included in the W3C CSS Test suite), I think it's time now to explain some guidelines for creating your own CSS tests.
jQuery: sliding content tabs
We want to create the effect of sliding content tabs. You click on a tab link and the corresponding content slides down and the slides to right into position. To get things smoother, we'll use the Easing plugin to add an additional effect to the
animate()
method. Let's see the details.
jQuery: Colorbox gallery tutorial
Colorbox is a powerful jQuery plugin for creating image effects based on the popular Lightbox effect. In its essence, it's a simple wrapper that you can call on the wrapper links of your images. Such links should contain the path to your full-sized image, while the images within them are usually thumbnail images. Let's see a practical example of a basic image gallery enhanced with Colorbox.
jQuery: creating a shopping cart effect
How can I add items to a shopping cart? This is the first question that pops into your head when you have to create a simple shopping cart with jQuery. In this post I'll answer to this question in the simplest way possible: using the
clone()
method. Before digging into the details, a short note on drag-and-drop: do not use this feature, because if you do so, you'll probably make things harder for your customers. Big companies such as Amazon don't use this feature in their shopping carts, so this is a good reason for avoiding this practice.
JavaScript: the Factory design pattern
The Factory design pattern is designed to create new object instances depending on the argument passed to the constructor. In JavaScript, the implementation of this design pattern is rather straightforward. All we have to do is to create a new function which accepts an object as its argument. Depending on the type of object passed in, it will return the appropriate object instance or an empty object if no argument has been specified.
jQuery: testing and debugging
During my daily work as a web developer, I usually deal with a lot of templates and site themes. Though they're pretty impressive from a visual point of view, they actually lack of consistency and organization when it comes to jQuery. The point is that many of these templates are not thoroughly tested and debugged in various environments. Usually the theme's author chooses a testing environment and a target browser and simply tests his/her code on that environment. Things run smoothly and the author assumes that everything will work just fine in other environments as well. Nothing could be more harmful than this approach. Environments and browsers are different and even though progressive enhancement can actually provide a fallback mechanism for the worst-case scenarios, you should never assume that a code tested in the browser X will work also in the browser Y. Here follows a little list of tips and gotchas to help you with testing and debugging in jQuery.
Wordpress: using the Google CDN version of jQuery
Using the Google CDN's version of jQuery with Wordpress is a task that requires only a slight change in your
functions.php
file. The only thing we have to check is that we're not viewing the Wordpress backend, where the default jQuery version is required. Let's see the code:
jQuery: rotating header images
Rotating header images is an easy task with jQuery. All we need is an array where to store our images, a JavaScript timer and the
fadeIn()
and fadeOut()
methods. Cycling through this array will produce the desired effect. Let's see the details.
jQuery: loading and executing code
jQuery's code can be loaded and executed either in the
head
or body
elements. Putting your jQuery code in the head
or body
elements of a web page is not the same thing. Though many developers follow the second approach to improve the overall perceived performance of their pages, they're probably not completely aware of the existing differences between the two methods. Let's take a closer look at them.
jQuery: Lavalamp menu tutorial
In this post I'd like to show you how to implement a Lavalamp-like effect on a menu from scratch. As you will see, all you need is some basic CSS declarations and just a few lines of jQuery code. I recommend you to test the proposed solution also in Internet Explorer and report any problem in the post's comment. Let's get to work.
jQuery: get a Wikipedia definition
Getting a definition from Wikipedia using jQuery requires only a PHP script used as a proxy to perform this task. This script will return a JSON object that we can parse with jQuery. I've used a general purpose function taken from this excellent article and I've actually modified it in order to make it return a JSON object. The PHP script is as follows: