Base JavaScript versus jQuery example – Driving a DOM selector

One of the things a good web programmer should be able to do is write code using multiple libraries. In this case I have created two snippets that show how to select an HTML on a page using both bare-bones JavaScript and its corollary in jQuery.

The basic flow is:

MouseEnter Listener -> Modify border -> Click Listener -> Call Function

MouseOut Listener -> Restore border

This gives you an interface where you can then select a DOM element right from the web page. It would look like this:

web-selection

Here are the two different implementations, you can see why I love jQuery, its brevity is breathtaking. The biggest difference is the selector API in jQuery that does the loop processing for you.

Base JavaScript

[codesyntax lang=”javascript”]

var all_1_Links = document.getElementsByTagName('div');
for (var i = 0; i < all_1_Links.length; i++) {
    var elm = all_1_Links[i];
    elm.addEventListener('mouseenter', function() {
        this.addEventListener('click', clickListener, true);
        this.style.oldborder = this.style.border;
        this.style.border = 'thin solid red';
    });
    elm.addEventListener('mouseout', function() {
        this.style.border = this.style.oldborder;
    });
}

[/codesyntax]

 

jQuery Version

[codesyntax lang=”javascript”]

$("div").mouseenter(function(e) {
    e.target.oldborder = e.target.style.border;
    $(e.target).css("border", "thin solid red"); 
    $(e.target).click(clickListener); 
}); 
$("div").mouseout(function(e) { 
    $(e.target).css("border", e.target.style.oldborder); 
    $(e.target).off("click"); 
});

[/codesyntax]

 

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s