[HTML5] API & jQuery

So far, I have used “document.getElementById()” function to retrieve the DOM element such as a <canvas> or <video>. If you are a jQuery fan, you might wonder how you can make use of jQuery more with HTML5 API. Let’s find out some tips here.

1. Converting jQuery Object to DOM Object

When you select elements in jQuery using “$()“, it returns a jQuery object, not a JavaScript DOM object. You can think of it as a wrapper object.

A jQuery object contains a list of matching DOM objects. (You know jQuery selects multiple elements.) And you can access each DOM object like an array. When you select a element by an “id“, it will return only one element.

Therefore, the first element is the DOM element object you want to access.

<script>
$(document).ready(function () {
  var video = $("#myVideo")[0];
  ...
  video.play();
});
</script>

<video id="myVideo">
The video cannot be played.
</video>

This technique works for the <canvas> too.

<script>
$(document).ready(function () {
  var cvs = $("#canvas1")[0];
  var cntx = cvs.getContext("2d");
  cntx.fillStyle = "rgb(255, 0, 255)";
  cntx.fillRect(30, 30, 400, 400);
});
</script>

<canvas id="canvas1" width="400px" height="400px">
A browser does not support.
</canvas>

 

2. Handling Events

Some HTML5 API is heavily dependent on events. The <video> is a good example.

Look at the traditional way to add event handlers.

function handleWhenPlayed() { alert("Playing"); }
function handleWhenPaused() { alert("Paused"); }
function handleWhenEnded() { alert("The end!"); }

var video = document.getElementById("myVideo");

video.addEventListener("play", handleWhenPlayed, false);
video.addEventListener("pause", handleWhenPaused, false);
video.addEventListener("ended", handleWhenEnded, false);

jQuery provides the better way to attach event handlers.

<script src="../Scripts/jquery.js"></script>

<script>
function handleWhenPlayed() { alert("Playing"); }
function handleWhenPaused() { alert("Paused"); }

$(document).ready(function () {
  var video = $("#myVideo");

  video.on("play", handleWhenPlayed);
  video.on("pause", handleWhenPaused);
  video.on("ended", function () { alert("The end!"); });

  var videoDOM = video[0];
  videoDOM.src = "../media/Video.ogv";
  if (videoDOM.ended) {
    videoDOM.load();
  }
  videoDOM.play();
});
</script>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s