Tuesday, July 23, 2013

jQuery Basics

JavaScript

JavaScript is a programming language that runs inside a browser.  Because it runs inside a browser, it runs on the user's machine instead of on the web server.  JavaScript code will respond much quicker to events like button clicks than code that runs on the server.  JavaScript also uses a technology known as AJAX to call server code without a time consuming post back.  Incorporating more JavaScript into your web site can speed up and improve the user experience.  However, JavaScript is ugly.  You sometimes have to jump through a lot of hoops to do simple things, including AJAX calls.

jQuery

jQuery is simply a JavaScript library.  It is literally just one file that you download at jquery.com.  It's free and open source (you can't compile JavaScript anyway).  The library contains a bunch of functions that you can call.  The functions do pretty much everything you would want to do with JavaScript, so every line of code you write is just a call to a jQuery function.

To use jQuery, you just need to reference the jQuery library with a line like the following in the head tag of your html page:

    <script type="text/javascript" src="jquery-1.10.2.js"></script>  

You should definitely keep your own JavaScript in a separate file as well:

    <script src="StevesJScript.js" type="text/javascript"></script>

Let's dive into an example to demonstrate how this all works.

Clicking buttons

First, add a text box, a few buttons, and a paragraph to display some results to your page:

   <input type="text" id="textBoxNumber" />  
   <button id="buttonPressMe">Press Me</button>  
   <button id="buttonClear">Clear</button>  
   <p id="results">results</p>

Instead of setting the event attribute on the actual tag, you can associate a click event in your JavaScript file by calling a jQuery function.  This almost feels like a "code-behind" page like you see with ASP WebForms.

$(document).ready(function () {

    $("#buttonPressMe").click(function () {
        $("#results").text($("#textBoxNumber").val())
    });

    $("#buttonClear").click(function () {
        $("#textBoxNumber").val("");
    });

});

The $ function selects an element.  In this case, we select the whole document.  Then we call the ready function for that element.  So this means, after the document loads, whatever is sent to the ready function will execute.  You can see we have selected both buttons by id (using the # symbol) and have called the click function which specifies what to execute when the selected button is clicked.  Here I am simply displaying the contents of the text box and clearing out the text box.

No comments:

Post a Comment