Archive for the ‘jQuery Tips’ Category

How to load css files with AJAX using jQuery

July 22, 2010

This week I was building a music player widget with jQuery and decided to make multiple skins available for people to choose from.

I figured I needed to dynamically load the css files with AJAX when the widget is initialized.

This is what I came up with:

<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
	$.ajax({
		url:"style.css",
		success:function(data){
			 $("<style></style>").appendTo("head").html(data);
		}
	})
})
</script>

jQuery and checkboxes, the complete guide.

July 14, 2010

jQuery is a great framework but sometimes the jQuery.com documentation is not enough to answer all your questions.
Here is a list of pretty much everything you can do with checkboxes.

Selecting / Unselecting a checkbox

// Check a checkbox
$('input[name=acheckbox]').attr('checked', true);
 
// Uncheck a checkbox
$('input[name=acheckbox]').attr('checked', false);

Selecting / Unselecting all checkboxes

// This will select all checkboxes
$("input:checkbox").attr('checked', true);
 
// This will unselect all checkboxes
$("input:checkbox").attr('checked', false);

Verifying if a checkbox is selected

// this will return true is the checkbox is checked, if not it will return false.
$('input[name=acheckbox]').is(':checked')

Getting a list of selected checkboxes

There are several ways to get a list the of selected checkboxes, here is my take on it.

// Extend jQuery with custom method
jQuery.fn.getCheckboxValues = function(){ 
    var values = []; 
    var i = 0; 
    this.each(function(){ 
        // push values into array
        values[i++] = $(this).val(); 
    }); 
    // return array of selected checkboxes
    return values; 
} 
 
var arr = $("input:checked").getCheckboxValues();
alert(arr); // this would alert an array containing the values of the selected checkboxes

How to make an HTML5 music player / Using the audio tag

July 7, 2010

There has been a lot of noise about HTML5 lately (thanks to Steve Jobs), but surprisingly few people actually know how and when to use HTML5 tags. Obviously one of the most talked about addition to HTML5 is the audio tag.

Here is a basic audio tag implementation:

<audio id="player" name="player" src="song.mp3" controls="controls">
</audio>

Simple and elegant right? Not really.

The Problem

Every browser has it’s own way of displaying the controls. If you look at the music player on safari, you’ll see a Quicktime player. If you look at it on Firefox, you’ll have a completely different look, same goes for other browsers including the iPad and iPhone.

The Solution

There is of course a solution to all this: Make your own controls.

The audio tag, like any other html element, can be modified via javascript. In other words,  you can play, stop, pause and load audio files remotely with simple javascript methods.

Below is a simple example of how to use Javascript ( jQuery in this case ) to control music playback with an html5 audio tag.

 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
 
<script>
	$(document).ready(function(){
		$("#play-bt").click(function(){
			$("#audio-player")[0].play();
			$("#message").text("Music started");
		})
 
		$("#pause-bt").click(function(){
			$("#audio-player")[0].pause();
			$("#message").text("Music paused");
		})
 
		$("#stop-bt").click(function(){
			$("#audio-player")[0].pause();
			$("#audio-player")[0].currentTime = 0;
			$("#message").text("Music Stopped");
		})
	})
</script>
 
<audio id="audio-player" name="audio-player" src="song.mp3" ></audio>
<div id="message"></div>
<a id="play-bt" href="#">Play music</a> | <a id="pause-bt" href="#">Pause music</a> | <a id="stop-bt" href="#">Stop music</a>

This is obviously a very basic implementation of HTML5 music player controls but you get the idea.

Important Notes / considerations

When deciding whether to use flash or HTML5 audio in your projects, always consider the following:

  • Because of format licensing issues, you cannot play mp3 files in Opera and Firefox. In other words you will need to have all your audio files in both .ogg and .mp3 format in order for everyone to enjoy it.
  • HTML5 penetration rate is still very low and will take years to catch up to Flash.
  • As you probably know, Flash is not compatible on the iPhone / iPad / iPod, so HTML5 has the advantage here.

More posts on HTML5 coming soon.

Selecting an object at a specific index with jQuery

July 6, 2010

As you probably know, the jQuery selector returns all the matched elements as an array. But what if you needed to select only the third element in the returned elements list?
The code below will return only the 3rd element in the returned selected list

// get 3rd item as a jQuery object:
$('div:eq(2)')
 
// get 3rd item as a pure DOM object
$('div')[2];

How to bind events in jQuery

I used to bind mouse events to dom elements using the .click() method like below:

$("a.button").click(function(){
	alert("A button was clicked");
})

The problem with this technique is that everytime a new button is added to the dom, you need to re-apply the click behavior to it.

Fortunately, jQuery introduced the .live() method in version 1.3 which solves that issue. The .live() method will bind an event to any element matching the selector now or at any point in the future, so if you you add new buttons to the page dynamically, they will also be binded to the event.

Use:as follows:

$('a.button').live('click', function(){
	alert("A button was clicked");
});

How to remove or empty elements in jQuery

Removing or emptying dom elements with jQuery

// Removes the element from the dom
$('selector').remove()
 
// Empties the element
$('selector').empty();

Note that this will empty or remove every element matched by the selector, so if you have 25 divs with the class “article-content” and you do $(’div.article-content’).empty(); , It will empty the 25 divs selected.

How to select children or parent elements in jQuery

Selecting Child or parent elements in jQuery is quite simple and powerful:

// Selecting child elements
$('selector').children('.class-name')
 
// or any other selector like:
$('selector').children('div span')
 
// Selecting the parent element
$('selector').parent()