Selecting DOM elements and Events with JQuery

Continuing with JQuery(refer previous posts on JQuery Introduction to JQuery and Watermark textbox with JQuery) , today I thought to write down a small article about selecting DOM elements and events in JQuery. This will show the power of JQuery, how easily you can play with the DOM elements on a webpage. JQuery uses CSS 3.0 syntax to select single or multiple elements.

Using CSS syntax means,

  • Select elements by ID
  • Select elements by CSS class
  • Select elements by attribute filter

Let’s take simple examples to understand what I mean,

Select element by ID, let’s say you have a paragraph tag on your page and its Id is “P1”.

<p id=”P1”>This a introduction to JQuery</p>

To apply a background color change on this paragraph tag only we need to write down the following line of code,

$(“#p1”).css(“background”, “lightblue”);

Similarly if we want to apply style sheet on textboxes on our page which are having using some specific stylesheet class we can do that in the following manner,

$(“.txtClass”).css(“border”, “solid 1px navy”);

Same way if we want to apply a style on all of paragraphs on our page we will do like this,

$(“p”). css({“color”:”white”, “width”;”100px”});

You can see how easy it is to play with DOM elements with JQuery. You can not only apply stylesheets but also can append DOM elements at runtime. Let’s look at the simple example how we are appending DIV tags at runtime and calculating the number of DIV tags.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head>
    <title>Welcome to JQuery</title>
    <script src=”script/jquery-1.4.1.js” type=”text/javascript”></script>
    <style type=”text/css”>
        div{width:50px;height:30px;background:blue;padding-top:15px;margin:5px;}
    </style>
    <script type=”text/javascript”>
        $(document).ready(function() {
            $(“#btn1″).click(function() {
                $(document.body).append($(“<div>”));
                alert($(“div”).size());
            });
        });
    </script>
</head>
<body>
<input type=”button” id=”btn1″ value=”Click to Count Div tags” />
<div></div>
 
</body>
</html>

In the above example we are appending DIV tags on click of button.  You can see how easy it is to append DOM elements with a single line of code. This is the beauty of JQuery.

Event handling in JQuery is quite easy. Before looking into next example of JQuery events, we will go through few features of JQuery events,

  • Classic Javascript event handling vary between browsers
  • JQuery event model for all supported browsers
  • JQuery event handlers take a function as parameter
  • JQuery provides easy mechanism for binding and unbinding events
  • JQuery provide common model for event handlers
    • The ‘this’ pointer always equals the element the event fired on
    • An event object is always passed as a parameter
    • Event object is a cross-browser  ‘normalized’
  • JQuery provides chain-ability


Lets look at the example below.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head>
    <title>Welcome to JQuery</title>
    <script src=”script/jquery-1.4.1.js” type=”text/javascript”></script>
    <script type=”text/javascript”>
        function ButtonClick() {
            $(“#table1>thead>tr”).css({“background” : “green”, “color” : “white”});
            $(“#table1>tbody>tr”).css({ “background”: “blue”, “color”: “white” });
            $(“#table1>tbody>tr:even”).css({ “background”: “gray”, “color”: “white” }).click(function(e) {
                alert($(this).find(“td:nth-child(1)”).text());
            });
        }
    </script>
</head>
<body>
<div>
    <input type=”button” id=”btn1″ value=”Button 1″ onclick=”ButtonClick()” />
    <br />
    <table border=”1″ id=”table1″>
        <thead>
            <tr>
                <th>Match</th>
                <th>Result</th>
            </tr>
        </thead>
        <tbody>
        <tr>
            <td>Barazil vs Dutch</td>
            <td>2 – 1</td>
        </tr>
        <tr>
            <td>Germany vs Argintina</td>
            <td>4 – 0</td>
        </tr>
        <tr>
            <td>Germany vs England</td>
            <td>4 – 1</td>
        </tr>
        <tr>
            <td>US vs Gayna</td>
            <td>1 – 2</td>
        </tr>
        </tbody>
    </table>
    </div>
</body>
</html>

In the above example what I did is that I created a table which shows result of a football tournament. When page gets loaded it will show plain table without any formatting. I placed a button above the table and on its register events with the button click event. You can see we are performing number of functions on click event and all are join together. Although it makes the code bit complex but it’s a quite handy feature of JQuery. Once you click the button you can see that table header and rows color gets change. Here we use the CSS 3.0 to put functionality on our page. Like to add color on header row we put $(“#table1>thead>tr”).css({“background” : “green”, “color” : “white”});

Similarly we change the table row colors to blue. Now you will see that there rows with gray color. If you look into this line $(“#table1>tbody>tr:even”).css({ “background”: “gray”, “color”: “white” })  you will see that for even rows of the table we put gray color. And for even rows we add a click function as well. In which we are fetching the first column value and showing it in alert.

There are number of built-in functions provided by JQuery(you can find more on JQuery site), which reduce the number of line of codes and makes our JavaScript more readable. Have a look at simple example below which is using toggle function of JQuery. I added the classic JavaScript function as well which Hide/Visible the paragraph. So that you can compare how easy it is to work with JQuery.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head>
<title>Welcome to JQuery</title>
<script src=”script/jquery-1.4.1.js” type=”text/javascript”></script>
<script type=”text/javascript”>
function winload() {
document.getElementById(“detail”).style.visibility = “hidden”;
}
function btn_click() {
var chkstatus = document.getElementById(“detail”).style.visibility;
if (chkstatus == ‘visible’) {
document.getElementById(“detail”).style.visibility = “hidden”;
}
else {
document.getElementById(“detail”).style.visibility = “visible”;
}
}
</script>
<script type=”text/javascript”>
$(document).ready(function() {
$(“#news2″).hide();
$(“#btn2″).click(function() {
$(“#news2″).toggle(“slow”).css({ “color”: “blue”, “font-size”: “11px” });
});
});
</script>
</head>
<body onload=”winload()”>
<p id=”Headline”>Today’s headline is… <input type=”button” id=”btn1″ value=”more” onclick=”btn_click()” /></p>
<p id=”detail”>Cardiologists once hailed it as a miracle worker: a gadget the size of a matchbox which, when inserted under the collarbone, can jump-start a dodgy heart. The implantable cardioverter-defibrillator (ICD), as it is called, is able to detect a dangerously abnormal heartbeat (arrhythmia) and, by giving the heart an electric shock, jolt it back into normal rhythm. Since their introduction in the Eighties, ICDs have been fitted in nearly 30,000 patients and have extended countless lives</p>
<br />
<p>The emotional side of choosing cosmetic surgery..<input type=”button” id=”btn2″ value=”more”/></p>
<p id=”news2″>When life hurts, instinctively we reach out to find things to fix it, to make the pain go away. Passed up for promotion? Cue, a sparkly pair of Kurt Geigers. Dumped by your boyfriend? Time for a snazzy new hair-do. We are programmed by our beauty-biased society to think, ‘If I look better, I will feel better’. Or, ‘If I look great, I’ll be able to cope with this.’ Now, with Botox and do-it-in-your-lunchtime cosmetic surgery procedures becoming more commonplace, increasingly women – and men – are reaching out to their friendly local plastic surgeon for an aesthetic boost.</p>
</body>
</html>

 

I am sure this post will be very handy to understand the basic concepts of JQuery.

 

Leave a Reply