Home > Tags > Document Object Model
Page 1

Carrying Out Tasks in the Background with HTML5 Web Workers

HTML5 offers a range of improved options for executing JavaScript functions. With Web Workers, you can execute scripts in the background, so that intensive processing need not interfere with the main functionality of your page. Of course this is most useful for complex tasks, but in this tutorial we will demonstrate the basics of using Web Workers with your pages using a simple example.

At the moment the most recent versions of all major browsers, except Internet Explorer, support Web Workers – you can’t rely on them just yet.

Create a Page

Let’s get stuck in and create an HTML5 page using the following outline:

<!DOCTYPE html> <html> <head> <script type="text/javascript"> </script> </head> <body> </body> </html>

We have our script section ready for the JavaScript code and will also create a separate script in which the Web Worker will run. Add the following elements to the body section of your page:

<input type="button" value="GO!" onclick="startWorking()"/> <input type="button" value="Stop" onclick="stopWorking()"/> <p>Here is your random word: <span id="random"></span></p>

Our Web Worker script is going to choose random words to display to the user at specified intervals. Notice that the two buttons for starting and stopping the Web Worker call different functions.

Start the Work

In the script section of your page head, add the outline of the function to start the Web Worker, as specified in your start button click listener:

//Web Worker variable var myWorker; //function to start the Web Worker function startWorking() { //function content here }

We declare the Worker variable outside the function so that we can refer to it in the stop function as well, which we will do later. Inside the “startWorking” function, first add the following checks to determine whether we have browser support:

//check for browser support if(typeof(Worker)!=="undefined") { //Web Worker is supported - call the script } else document.getElementById("random").innerHTML = "Oops! Your browser doesn't support this.";

We will add code inside the “if” statement to call the Web Worker script, with the “else” statement executing if support is not present, in which case we simply output an error message to the user. In the “if” statement block, add the following to instantiate the Web Worker:

//instantiate the Web Worker object if(typeof(myWorker)=="undefined") myWorker...
more →
Dominik Werner says: Hum, I'm still searching for a way to prevent my js/html5-based experimental metronome from losing its beat when changing tabs....

Using Custom Attributes in HTML5

Custom attributes are among the most significant additions for HTML5, and can play a major role in semantic Web development. In this tutorial we’ll go through a practical example of creating and accessing HTML5 custom data attributes, including the necessary JavaScript functions.

It was possible before HTML5 to add your own attributes to HTML elements and access them using JavaScript, but if you’ve ever tried it you’ll know you can forget about getting your markup to validate. HTML5 provides the ability to create and use your own element attributes within valid pages.

Create Your HTML5 Document

If you don’t already have one you want to use, copy the following outline into an HTML file:

<!DOCTYPE html> <html> <head> <script> /*functions here*/ </script> </head> <body> </body> </html>

We will place our elements with custom attributes in the body and the JavaScript functions for accessing them in the head section script area.

Create an Element

Let’s add an element with some simple content and a custom attribute as well as an ID so that we can identify it in JavaScript for demonstration:

<div id="product1" data-product-category="clothing"> Cotton Shirt </div>

As you can see, the custom attribute has the form: “data-*” with a name or names of your choice after the “data-” section. This is the only valid way to use custom attributes in HTML5, so make sure you start your elements this way if you need your pages to validate.

Of course the details of your own projects will dictate whether custom attributes are useful to you, as well as how to go about naming them. This example could be for a retail site with different product categories. The custom attributes allow you to treat elements in particular ways within the JavaScript code for the page, for example when using animated display functions. It’s really only advisable to use custom attributes if there is no standard HTML attribute available to do what you need.

Add a Test Button

Your own JavaScript functions will execute on events within your pages, but to demonstrate add the following button to your page:

<input type="button" value="get attribute" onclick="getElementAttribute('product1')"/>

The button passes the element ID as parameter, so that the JavaScript function can refer to it and access its custom attribute.

Get the Attribute

The most common way to access attributes in JavaScript is using “getAttributes” which is what we’ll do first. Add the following function in the script section of your page head:

function getElementAttribute(elemID) { var theElement = document.getElementById(elemID); var theAttribute = theElement.getAttribute('data-product-category'); alert(theAttribute); }

We alert the attribute value for demonstration, but your own scripts can do whatever you need with it.

Get the Dataset

As an alternative to the DOM “getAttributes” method, you can use the element dataset. This can be more efficient, particularly in cases where your code is iterating through a variety of attributes. However, browser support for dataset is still very low, so do bear this in mind. This code carries out the same process as the line commented out from the previous approach:

//var theAttribute = theElement.getAttribute('data-product-category'); var theAttribute = theElement.dataset.productCategory;

With dataset you remove the “data-” from the start of the attribute name when referring to it in JavaScript – you do still need to include it in your HTML though. Notice that if your custom attribute name has a hyphen in it, which ours does, this becomes camel-case when accessed through the dataset (“data-product-category” becomes “productCategory”).

Other Methods and Functions

We have explored getting attributes, but your scripts can also set and remove them. The following code demonstrates setting attributes using the standard JavaScript method and the dataset alternative:

//DOM method theElement.setAttribute('data-product-category', 'sale'); //dataset version theElement.dataset.productCategory...
more →
Mohit Saxena says: http://www.expertsfromindia.com/html5-development.htm" rel="nofollow">html5 development allows effortless usage of...

What Can You Do With Paper.js?

There are many JavaScript frameworks that leverage HTML5.

Paper.js is one of these frameworks that uses Document Object Model (DOM) to structure objects in an easy-to-understand manner.  It offers creative and neat ways of doing lots of stuff on a Web browser that supports the <canvas> tag. It also offers a new and interesting approach to drawing vector graphics.

The basic setup is shown below:

<script src="js/paper.js" type="text/javascript"></script> <script src="js/main.js" type="text/paperscript"></script> <canvas id="draw" width="100%" height="100%" resize="true"></canvas>

As you can see, the paper.js is included after which you add your code file under “type=”text/….” After passing the canvas element id that needs to be drawn and ensuring that your code file includes all the classes and functionality to be used with paper.js, then the rest is a matter of being creative while you leave the rest to paper.js.

Working with Predefined Shapes

Paper.js allows you to use predefined shapes of varying dimensions and create path items and segments. For example, the code below produces circle-shaped paths from the “Circle” constructor:

var myCircle = new Path.Circle(new Point(300, 70), 50); myCircle.fillColor = 'black';

This piece of code creates a black circle with a radius of 50pts and at the x position of 300 and a y position of y.

To create a rectangle, you pass the “Rectangle” constructor the same way as a circle as shown below:

var rectangle = new Rectangle(new Point(50, 50), new Point(150, 100)); var path = new Path.Rectangle(rectangle); path.fillColor = '#e9e9ff'; path.selected = true;

Creating Interaction

Paper.js also supports drag n drop functionality as well as keyboard strokes. An empty path is created on execution where segments can also be added as shown below:

// Create a new path once, when the script is executed: var myPath = new Path(); myPath.strokeColor = 'black'; // This function is called whenever the user // clicks the mouse in the view: function onMouseDown(event) { // If the path is empty, we need to add two segments // to the path. The first one will stay put, // and the second...
more →
David Gitonga says: Hi Rokcy. Here is the demo link. http://paperjs.org/examples/ The link contains different animations created using Paperjs.

Switch on With jQuery’s New Event Methods

The latest version of jQuery, version 1.7.1 at the time of writing, has completely overhauled its event system, giving us just two new methods to replace all existing event methods such as bind(), live() or delegate().

Event handling has been a core part of jQuery for a long time, but over the years the jQuery event landscape has flourished and grown, with successive releases increasing the number of methods for handling events.

The new event methods on() and off() condense these different methods down into a single unified API. Instead of having different methods to handle different behaviours, the new methods simply behave differently depending on how they are called.

Attaching events like bind()

Attaching an event using the on() method in the same way as if we had used the bind() method can be done like this:

$("#button1").on("click", function () { //do stuff });

When just two arguments are passed to the on() method the event handler is attached directly to the selected element. In this example the button with an id of button1 will have a click-handler attached to it, which will execution the function passed as the second argument whenever the event is detected. This is equivalent to the now deprecated bind() method. Alternatively, we can attach multiple events by supplying a single argument to on():

$("#button1").on({ click: function () { //do stuff }, focus: function () { //do stuff } });

The argument we pass to the method accepts an object where the keys are event names, and the values are anonymous functions that are executed when the events are detected. Again, this is exactly how we could have previously used bind().

Attaching events like delegate()

In its other form, the on() method accepts three arguments:

$("#delegateContainer").on("click", "button", function () { //do stuff });

In this form the on() method accepts an extra argument. The first argument is still the name of an event (or a space-separated list of events) to listen for, but the second argument is now a selector to filter by. The third argument is the function to execute when the event (or events) is detected.

What happens is; the container element that is initially selected (“delegateContainer” in the above example) has the event handler attached to it. When the named event is detected jQuery checks to see whether it originated from the element matching the selector passed as the second argument. If it does, the function is executed.

Just like with the delegate() method, we can use any CSS selector, DOM node or jQuery object as the second argument. This is a major step up from the live() method, which was restricted to just CSS selectors. However, the value of $(this) within the event handler changes depending on what you pass as the second argument; if you pass a CSS selector, the $(this) object points to the innermost element that triggered the event (in this example, the button that was clicked). However, if you pass a DOM node or jQuery object, $(this) will point to the container that the event was delegated to. Watch out for this when coding.

Event delegation in this way brings several benefits; firstly, it can allow us to vastly reduce the number of event handlers that are attached to elements – we could have hundreds of buttons within our delegateContainer, but we would still only need to attach a single handler to the container, and any button would trigger it when clicked. Secondly, if we attached new buttons at some point in the future, after we had attached the handler, the new buttons would still trigger the event handler without us having to rebind it.

As well as the arguments we’ve looked at, the on() method can also accept a data object, which will available within the callback function as event.data. This argument should be passed to the method as either the second or third argument depending on whether a CSS selector is also provided, for example either:

$("#button1").on("click", { someKey: "someValue" }, function (e) { //someValue available via e.data.someKey });

Or:

$("#button1").on({ click: function (e) { //someValue available via e.data.someKey } }, { someKey: "someValue" });

Or, with event delegation:

$("#delegateContainer").on("click", "button", { someKey: "someValue" }, function (e) { //someValue available via e.data.someKey });

Removing events

To remove a bound event handler, we can use the off() method, which is the new replacement for the unbind(), die() and undelegate(). The off() method also takes a varying number of arguments; if a CSS selector was passed to the on() method, the same selector should be passed to off(). To remove the delegated event handler, we could use the following code:

$("#button3").on("click", function () { $("#delegateContainer").off("click", "button"); });

The off() method is almost identical to the code we used with the on() method from the last example, except that we don’t provide a callback function. If we don’t supply a CSS selector to the on() method, the off() method can be even simpler, with just the name of the event to remove the handler from.

Summary

The old event-handling methods live(), bind() and delegate(), and their opposite unbinding methods, are all now deprecated; they’re still available to use through the core jQuery API of course and will remain there for some time yet, but their use is advised against now that we have on() and off() to take care of all our event handling needs.

...
more →
Greg says: I've noticed that a tonne of people still want to use .live() even though it's a performance nightmare. Although I always advise...

How To Change A Page’s Background As The User Scrolls

jQuery is great for adding enhancing effects that would otherwise be impossible with just HTML and CSS. In this tutorial we’re going to use jQuery and two plugins to gradually change a website’s background as the user scrolls the page.

We’ll be using the Color Animation and Waypoints plugins. The Color Animation plugin adds animations to the color properties of elements. jQuery already includes an animate function, this plugin simply extends it. The Waypoints plugin allows us to execute a function when a user scrolls past a certain element. I’m sure it’s obvious how these two plugins will help us achieve our goal.

First things first, let’s set up our project folder. Create index.html and style.css. Leave them in the root directory. Then, add a js folder. This is where we’ll put our JavaScript files.

We can grab the newest version of jQuery here and put it in the js folder. Next, create a script.js file in the js folder.

We’ll use script.js to add the Color Animation and Waypoints plugins. Get Color Animations from here and Waypoints from here. We can paste these two plugins directly into our script.js file.

The Markup

The HTML markup in this tutorial is going to be very simple. We’re just going to have a bunch of paragraphs and headings. The idea is to simulate a fairly long page so we’ll have a lot to scroll through.

Start by adding this code to index.html:

<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="style.css"/> </head> <body> <div class="container"> </div><!-- end container --> </body> </html>

This gives us a nice basic structure to start from, but remember, we need to include our JavaScript files too. Before the closing head tag, add these two lines:

<script src="js/jquery-1.6.2.min.js"></script> <script src="js/script.js"></script>

Inside the div with the class container add the following code:

<h1>A Story About Colors</h1> <h2 id="chapter1">In The Beginning, There Was Yellow</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit accum. Sed a ornare massa. Donec ac sapien a sem aliquet facilisis. Nulla vitae nunc tortor, at luctus risus. Integer viverra sapien a nibh condimentum sed luctus lorem interdum. Aliquam...
more →
Leo Aljiro says: Demo would be nice but I can see you really want us to try it out on our own to see the effect. Either way useful tutorial....

New methods in jQuery 1.6

jQuery is an actively-developed JavaScript library with a fairly rapid release cycle. As well as general enhancements, performance tweaks and bug fixes, new methods are frequently added to the library.

In this article we’ll take a look at the new methods that have been added to the 1.6+ release and some of the enhancements.

Delaying the ready event with the holdReady() method

The holdReady() method is used to delay the firing of jQuery’s ready event, a cornerstone event which is popularly used to execute custom code once the DOM is ready to be manipulated. As of jQuery 1.6 we can now postpone the triggering of this event for an arbitrary length of time in order to wait for other conditions to be satisfied, such as the loading of a plugin.

It’s a dual-purpose method, as is the jQuery way, and can be used to both delay the event and release the event using the same simple signature. The method accepts a Boolean argument which specifies whether the event should be held or released.

One downside to this method is that it should be called as early in the document as possible, such as in the <head> of the page, and can obviously only be called after jQuery itself has loaded. As we know, for performance reasons, scripts should usually be placed as close to the end of the document as possible, so moving jQuery to the <head> should only be considered when absolutely required.

Using holdReady() is super easy; as early in the document loading as possible simply call the method with the value true as the argument:

jQuery.holdReady(true);

Then, once the additional file(s) you require have loaded, call the method again with the value false:

jQuery.holdReady(false);

Adding and removing element properties

The prop() method is a way to explicitly retrieve element property values. There is a subtle difference between properties and attributes and this difference used to cause occasional issues when trying to get or set property values using jQuery’s attr() method.

The classic example is with checkbox elements; there were sometimes issues when trying to dynamically set the checked property using the attr() method. When the prop() method was released in version 1.6 the attr() method was changed so that it retuned only the initial state of the property, however this was changed in the 1.6.1 release so that it also returns the current state when using attr(). To use the prop() method we use the same syntax as with attr():

$("input[type='checkbox']).prop("checked");

The method in this format returns the current value. To use the method in setter mode we just supply a second argument specifying what we would like the value to be.

The prop() method can also be used to set custom properties on elements, and you should note that the method only returns the property value for the first element in a collection, not each element in the collection.

To remove custom properties, the new removeProp() method is also available since jQuery 1.6. This method should only be used to remove custom properties; if native properties are removed it is not possible for them to be re-added. Custom properties should always be removed before the element that they have been added to is removed from the DOM in order to prevent memory leaks in old versions of IE.

Promise objects

The new promise() method returns a promise object that can be used to execute arbitrary code once all actions on each element in the collection the method is attached to have completed. By default the promise object monitors fx queues, but custom queues can also be specified by supplying an optional first argument to the method. The object that the promise methods are attached to can also be specified using an optional second argument to avoid creating a new object.

The method can be used in conjunction with methods such as done() to execute a function when all animations on an element have completed:

$("#animated").promise().done(function () { //do stuff });

A new selector

We can now make use of the :focus pseudo-selector to select a focused element, or determine whether an element has focus, a great new addition that could help save on convoluted work-arounds.

New deferred methods

jQuery 1.6 brings two new methods for use with deferred objects; the first is the always() method which can be used to execute a function regardless of whether the deferred object is resolved or rejected. The second new method is pipe(), which can be used to filter deferred objects either when they resolve or fail. The method returns either a filtered value which can be passed to the done() or fail() methods of the deferred object the pipe() method is attached to, or a new promise object.

Method updates

In addition to the totally new methods we’ve looked at so far, some of jQuery’s existing methods have also been modified, these include:

attr() This method now returns undefined when retrieving an attribute that has not been set closest() This method now accepts jQuery elements and DOM nodes as the filter find() This method now accepts jQuery elements and DOM nodes as the filter Is() This method now accepts jQuery elements and DOM nodes as the filter map() This method can now iterate over objects as well as arrays nextUntil() This method now accepts jQuery elements and DOM nodes as the filter parentsUntil() This method now accepts jQuery elements and DOM nodes as the filter prevUntil() This method now accepts jQuery elements and DOM nodes as the filter Undelegate() This method can now unbind all...
more →
Kaloyan Banev says: jQuery is one of my favorite frameworks, probably same apply for MooTools. Recently I've checked different libraries, but none is...

Implement an Image Slideshow Using a jQuery Plugin

Image slideshows are a dime a dozen on the web.

You see them used for advertisements, featured articles, product showcases, and plain old photo reels.

Today, we’re going to quickly implement a slideshow using the jQuery plugin Cycle by Mike Alsup.

Cycle is a great plugin with years of development behind it. We’re going to use the Lite version. It lacks some of the features of the full version (like different transitions), but it is super lightweight. While the full version is 49kb, the lite version weighs in at only 8kb.

Let’s begin by creating a project folder. Within this folder create two text files and rename them to index.html and style.css. Also, create two sub-folders named js and img. This is where we will put our javascript files and images, respectively.

Next, we’re going to need the JavaScript library jQuery and the Cycle plugin file. Download the latest version of jQuery here and Cycle here. Put them both in the js folder.

Note: If the files open in your browser as text, right-click the link and “Save as.”

Find, or create, five images for your slideshow and place them in the img folder. Make sure they are all the same size for now.

The Markup

Now, using your favorite text editor, open index.html. Paste the following code in:

<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="style.css"/> </head> <body> <div> </div><!-- end container --> </body> </html>

The above code sets up a basic HTML file and includes our stylesheet. We also need to include our JavaScript files. Before the closing head tag, include the following lines:

<script src="js/jquery-1.6.2.min.js"></script> <script src="js/jquery.cycle.lite.js"></script>

Now index.html should look like this:

<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="style.css"/> <script src="js/jquery-1.6.2.min.js"></script> <script src="js/jquery.cycle.lite.js"></script> </head> <body> <div> </div><!--...
more →
Jens Grochtdreis says: This slideshow is nothing more than a list of images which is presented one after the other. So why don't you use an ordered or...