Using jQuery Variables to Build an Interactive Website

Javascript and jQuery for Web 2.0 shutterstock_133638464

Modern web applications, built in web 2.0 technologies, allow using complex software applications via the Internet, as alternatives to desktop based software. Web applications in social media space, like Facebook, Twitter, and Google+ enable rapid sharing of information while serving as a common whiteboard medium to learn and share information. In their editing, formatting and rendering powers provided without installing much software – by primarily running software in the sandboxed environment of a web browser – the web apps provide the new paradigm of delivering software on Internet.

Javascript provides the client-side interactive part of the web applications. jQuery is a specialized light-weight library which provides cross platform, multi-browser compatible API, you may develop your web-app in Javascript. In this blog post, we show you how you can get started toward building your own client-side interactive applications using jQuery variables, and post some data to the web server. 

Power of Web Apps

Web applications include music players – iTunes from Apple, streaming music services like Google Music, Pandora and Spotify, video/audio players which have taken over tradition desktop music player applications.

With advent of cloud computing, these web applications can synchronize user data across multiple platforms and devices providing a seamless user experience. Editing and hosting applications for streaming services like Sound Cloud, Youtube, Vimeo are examples of web applications which provide consistent user experience across devices – some used to record video, others to view video and yet others to edit and format it – but of it enabled by the same web platform.

Online giants Google and Facebook, who make their money primarily through gathering user data, sell advertisements to targeted demographics by using javascript based web software. Different parts of their web services collect user information, authenticate, log, and serve advertisements.

Javascript allows building portable, accessible. And interactive. Libraries for javascript like jQuery, Dojo or Angular.js make this process fast and easy.

Javascript – The Programming Language

Javascript is a programming language is primarily used to add interactivity to static HTML pages, but scripting the document-object-model (DOM) of the web page, in the browser that is rendering the web page. This is also called client-side programming.

Advanced uses of Javascript include libraries like node.js, which render a webpage on web server, using Javascript effectively as a server-side language. This is however, not the focus of this article.

Typically a javascript is loaded by the web browser after the web page elements static HTML, resource images and video are loaded.

Applying jQuery – Interactive Design

Show/hide – toggle visibility – of the widgets, images, triggers etc.

Typical uses of jQuery include

  1. Form element validation

  2. Calculations on button click or document event callback

  3. Perform animations on DOM elements

  4. Post back form data to server of origin

  5. Update parts of web page asynchronously using AJAX

  6. Highlight selections or widgets, or gray them out for guidance

  7. Add/remove widgets based on choice.

  8. Using timers and timeouts in javascript

Loading jQuery Library

In the HTML page, within the the ‘<head>’ section in a ‘<script>’ tag you can load the jQuery file from one of the content distribution networks (CDN) by the following element,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.js"></script>

This tag asks the browser to download jQuery v1.8 from the Google CDN.

Using jQuery Variables

Jquery provides a shortcut variables to access, create and modify, DOM elements of the web page using the class or id attribute selectors. Typically the selector object is accessible by special variable ‘$’. The key point of the selector object is the fact that every object method invocation returns a reference to the same ‘$’ object.

Selector Notation

jQuery identifies the DOM elements by using the CSS style selectors for a class of DOM elements, or specific elements by ID. For example, if a HTML page had a check box form element with ID attribute ‘kbd’

<input type=”checkbox” id=”kbd” onClick=”javascript:showStatus();”/> click me</input>

we would be able to access its value (i.e. checked or unchecked) by the following javascript code,

<script>
 var showStatus = function() {
 window.alert('value[ kbd ] = '+$('#kbd').prop('checked')); 
 }
</script>

which basically runs everytime a user clicks on the checkbox and prints the state of the DOM element with ID attribute ‘kbd’. $(‘#kbd’) is the jQuery selector, and we access its property ‘checked’. We can also set the property of the element to true, using the notation,

$('#kbd').prop('checked',true);

same notation holds for other property value pairs and attributes associated with the element.

Using ‘onLoad’ Event

To run functions when the web page has finished loading, you may use the OnLoad attribute of the body tag, or you can simply write,

<script>
var onload_callback = function () {
window.alert('Hello World!')
}
$( onload_callback ); //setup the onload callback at end of page load.
</script>

Example : Temperature Converter Web Application

In this code we will calculate the temperature in Centigrade given the temperature in Fahrenheit, using the formula C = (F-32)*9/5. Copy paste the following code in a text file, download the jquery.js file into the current folder from jquery.com, and then fire off the chrome or firefox browser and look at your new web-application.

 <html>
 <head>
 <script src="./jquery.js"></script>
 <script type="text/javascript">
 var init = function() {
 console.log("Init fcn");
 };
var calc = function() {
var F = $('#tempF').prop('value')/1.0;
var C = (F - 32.0)*5.0/9.0;
console.log('Calculating F2C for '+F+' *F')
window.alert('clicked = '+C.toString());
$('#tempC').prop('value', C);
return $('#tempC').value;
};
</script>
</head>
<body onload="init();">
Temperature in degrees <input type=”text” id="tempF" value="212" /> <sup>*</sup>F<BR />
<input type=”text” id="tempC" /><sup>*</sup>C<BR />
<button onclick="javascript:calc();" id="calcF2C">Calculate</button><BR />
</body>
</html>

This renders on the system like,

Temperature in degrees [ 212  ] *F
[ 100            ] *C

We illustrate clearly the two functions, init, and calc, which are callback for onload() event, and the button click event. init() function writes a welcome message to the debug log window every time the page is loaded. Calc() function gets the values from the entry tempF, and updates tempC entry in the DOM with the calculated temperature in Centigrade.

Try this app with F=212, and F=32. What is the boiling point of water in Centigrade? What is the freezing point of water in Centigrade ?

Learn More

  1. The jQuery framework is hosted at http://jquery.com with current (latest) and past software releases available for download under the MIT license. Web programming couldn’t be easier!

  2. Various 3rd party plugins for jQuery from jQuery UI providing widgets and animations, Cookies plugin providing easy set/get/access to cookies and many more are available under similar OSS (open-source license) terms.

  3. Good references on JavaScript include Brian Flanagan’s ‘Definite JavaScript,’ which also talks about jQuery in the later sections.

  4. Debugging javascript is still challenging; you will need a modern browser like Firefox or Chrome, and use their plugin, e.g. Fire Bug with Firefox, and the javascript console to know your code works.

  5. jQuery allows making asynchronous programming easier by using the $.ajax() call. This mechanism relies on the XMLHttpRequest compatibility of the modern web browser.

  6. CDN are available for jQuery from various vendors like Microsoft, Google etc. if you choose to save bandwidth on your webhost by using a ‘minified’ (compressed) version of the javascript.