Tag Archives: jquery

Looping Animation with JavaScript and Raphaël

Raphael is a popular JavaScript library helping you to manage vectors via SVG or VML in your browser. It is extremely helpful and very easy to learn and use. The interesting thing is that in the browser you can do very powerful things with vectors, but they remain very less known. However with such libraries like Raphael the task is really simple.

Animation

As I said animating some vector properties is as simple as:

var paper = Raphael('canvas', 1024, 500);
var c = paper.circle(50, 50, 6).attr({fill : '#f00'});
c.animate({r : 10, fill : '#00f'}, 1000);

Here we change the radius and the background color of the circle for 1000 milliseconds.

The same thing can be done with any property with any other JavaScript library as jQuery. But as in jQuery, Raphael or whatever library the animation is not looping. That’s natural you can just change a property by animating it, but the looping animation suggests at least two animations. So it’s a developers job to implement this. Here’s a simple way to do this.

Two Way Animation

The solution here is using two functions calling each other.

var paper = Raphael('canvas', 1024, 500);
var c = paper.circle(50, 50, 6).attr({fill : '#f00'});
 
function a() {
    c.animate({r : 10, fill : '#00f'}, 1000, b);
}
function b() {
    c.animate({r : 6, fill : '#f00'}, 1000, a);
}
a();

jQuery: Get the Selected Option Text

What’s the Task?

First of all let me explain what is the task. If there’s a select menu with several options, each of which are with a given value attribute, the task is to get the text into the option tag, and not that of the value attribute.

In that scenario let’s assume that we have the following HTML:

<select id="my-select">
    <option value="1">value 1</option>
    <option value="2">value 2</option>
</select>

select menu
Note that in the official jQuery doc page, the selector is described in the same context, but with a different markup:

<select id="my-select">
    <option>value 1</option>
    <option>value 2</option>
</select>

than the jQuery snippet looks like that:

$(document).ready(function() {
    $("#my-select").change(function() {
        alert($(this).val());
    });
});

Here’s interesting to note that there’s no value attribute set to the options, thus the selection of an element is correct and the returned value is correct. The problem is that this code doesn’t work correctly once you’ve a different value attribute, from the value enclosed into the option tag. In our case we’ve the markup shown on the first code snippet and we’d like to get the “value 2” string instead of “2”.

Source Code

<select id="my-select">
    <option value="1">value 1</option>
    <option value="2">value 2</option>
</select>
$(document).ready(function() {
    $("#my-select").change(function() {
        alert($(this).val());
    });
});

Solution

Finally the solution, is pretty simple and clear, but this time is not to so “native” and it’s definitely something you couldn’t expect! The only thing you’ve to do is to change the selector!

$(document).ready(function() {
    $("#my-select).change(function() {
        alert($('#my-select option:selected').html());
    });
});

Speed Up the jQuery Code: Selectors’ Cache

Short Experiment

Here’s a short optimization of a small chunk of jQuery code. The experiment was to increment the number of DOM element access. In this case this was a change of the innerHTML property – using the $.html() method.

I’ve measured the result with the console.time() method and thus I expect correct results for both cases. In the first case I directly call the jQuery selectors’ html() method:

for (var i = 0; i < 10000; i++) {
    $('#container').html(i);
}

While in the second case I “cache” it before the loop:

var t = $('#container');
for (var i = 0; i < 10000; i++) {
    t.html(i);
}

and here’s the full code in the first case:

<html>
<head>
    <title>jQuery Cache</title>
</head>
<body>
 
<div id="container"></div>
 
<script src="/scripts/library.js"></script>
<script>
 
$(document).ready(function() {
 
    console.time('foo');
    for (var i = 0; i < 10000; i++) {
        $('#container').html(i);
    }
    console.timeEnd('foo');
});
</script>
</body>
</html>

The Results

As expected the second “cached” approach gave better results. With the increment of the iterations the second method began to be slightly better than the first one. That’s not so much, but imagine you have more than one selector in the loop’s body?

Numbers:


Note that in the time is in ms, and, yes, this is not so much, but when you deal with large data and you’ve more than one selector in the loop’s body, this can be critical!

Graphics:

Build a List Tree with the Beauty of jQuery

This is nothing useful, but let me show the beauty of jQuery. This snippet just adds more and more nodes on a simple UL based tree.

Here’s the HTML:

<ul>
    <li><a href="#">Node 1</a></li>
    <li><a href="#">Node 2</a></li>
    <li><a href="#">Node 3</a></li>
    <li><a href="#">Node 4</a></li>
</ul>

And that’s the jQuery:

var index = 5;
$('li > a').live('click', function() {
    $(this).parent().append('<ul><li><a href="#">Node ' + index + '</a></li></ul>');
 
    index++;
 
    return false;
});

And here’s the demo.

Detecting Pressed Key with e.which in JavaScript

You have definitely decided to get which key has been pressed with JavaScript? This is very common when it comes to an Enter key press over a form element. Actually this should be automatically done by the browser, but when it comes to a default prevented form you’ve to check it for yourself.

The job can be done with a event’s which check. Let me show you some JavaScript/jQuery code:

$('.selector').click(function(e) {
	console.log(e.which);	
});

Note that this can be checked under Firefox and/or Safari like browsers which support the console object. This will give you the idea which key is pressed in a number value. The Enter is usually 13!
If you don’t have such browser, you can replace that code with something like:

$('.selector').click(function(e) {
	alert(e.which);	
});