Category archive: jquery
Say you’re building a game with HTML and jQuery and you want to throw in some sound effects. Before HTML5, you had to resort to a pretty hacktacular approach:
$("#sound").remove(); var sound = $("<embed id='sound' type='audio/mpeg' />"); sound.attr('src', 'beep.mp3'); sound.attr('loop', false); sound.attr('hidden', true); sound.attr('autostart', true); $('body').append(sound);
This sucks for a lot of reasons, and it’s going to be a nightmare to build something that uses a lot of sounds.
HTML5 makes it super easy:
var snd = new Audio('beep.mp3'); snd.play();
Unfortunately I couldn’t get this to work on the iPad. After some digging around I found the answer buried in a Stack Overflow thread. You just have to do snd.load() before you call the play() method.
So, here’s some code that will take care of this, with our lame support for older browsers:
function html5_audio(){ var a = document.createElement('audio'); return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, '')); } var play_html5_audio = false; if(html5_audio()) play_html5_audio = true; function play_sound(url){ if(play_html5_audio){ var snd = new Audio(url); snd.load(); snd.play(); }else{ $("#sound").remove(); var sound = $("<embed id='sound' type='audio/mpeg' />"); sound.attr('src', url); sound.attr('loop', false); sound.attr('hidden', true); sound.attr('autostart', true); $('body').append(sound); } } play_sound('beep.mp3');
If you deal with the same handfull of elements over and over again on the same page, doing those $('.class_name') selections can put a lot of load on the browser (especially IE). Here’s an easy way to cache those objects without doing any extra work:
var el_cache = {}; function e(a){ if(el_cache[a] != undefined) return el_cache[a]; el_cache[a] = $(a); return el_cache[a]; }
Then you would just change your jQuery calls from this:
$('.class')
to this:
e('.class')
Obviously there are more jQueryish ways of doing this but come on, you can’t beat that simplicity.