Recently I was doing some heavy-duty Javascript stuff for a web project. It was quite a while since the Firefox plug-in and in many ways, it was rather enjoyable experience (and in some other ways boring
).
If you want to do some cool stuff in the web nowadays, the adoption of a Javascript library like jQuery is typical. I had some experience in the past, but the development process showed me that I was not so experienced as I thought. jQuery has good documentation that can be used as a reference, but it is not very usefull, when you want to understand some basic concepts and you are in a hurry of doing some stuff to work.
So, this blog entry has one goal, to transfer my experience of doing stuff with jQuery as a set of rules/advices that will save time to inexperienced users like me.
Rule #1: “When you are using jQuery, forget low-level Javascript functions”
It is a good practice to use always jQuery’s functions to do the stuff you want. Never rely on the low-leve Javascript function. The reason is simple. jQuery offers an encapsulating object for all the elements of the DOM tree. If you select some nodes with the jQuery selectors and then try to access their children with the common DOM function offered by the standard Javascript API, you are done for. You lose that encapsulation and you are back in black.
Rule #2: “Use # for the ‘id’ selector, ‘.’ for the class selector and always use backslashes in front of dots in ids”
No special reason, just remember these three examples:
- $(‘#theCoolId’) – id selector
- $(‘.myBigFatClass’) – class selector
- $(‘#theCoolId\\.With\\.Dots’) – more complex id selector
Rule #3: “When you have to insert code into an element, use html()”
Simple as that, select the node and paste the code:
$('#theCoolNode').html('
<h1>Hey Stranger!</h1>
');
Rule #4: “By default the ajax() call is asynchronous”
… so if you want to load something, be sure to disable async, or else you will try to access something that is not ready. How can you do that? Simple!
$.ajax({
type: "GET",
dataType: "xml",
url: "data/strings.xml",
success: function(xml) { /* success */ },
error: function() { /* error */ },
async: false /* I will wait to load the XML */
});
Rule #5: “insertBefore() and insertAfter() take the selector as the parameter”
I do not know about you, but I always thought that it is logical for the insertAfter() and insertBefore() to select a node, then append the node. But this is not the way they are implemented. A small example:
$('<h1>Hey Joe!</h1>').insertAfter('#theCoolNode')
Rule #6: “It is always your fault”
Usually it is, accept it and try to understand how things are working
, instead of trying to convince everyone that you are Mr. Right!
VN:F [1.9.14_1148]
Rating: 8.0/10 (1 vote cast)
VN:F [1.9.14_1148]