Purpose of using jQuery
How jQuery works – A First Example
Let’s start by creating a simple HTML page which displays a welcome message when the page loads.
The ready event from the above code is one of the many jQuery events. This event makes sure that any function or handler supplied to this event gets executed after the DOM is fully loaded. Thus, in the above example, the alert message is shown only after DOM is completed loaded.
A realistic jQuery Example
In this example we will hide or show a particular content based on toggle key selection.
In the above example we have one HTML div tag with id of myDiv and a simple button with id of toggle and default value of ‘Hide’. Upon clicking the button we’re hiding the div myDiv and at the same time we’re changing the button’s value to ‘Show’. Clicking again the button will eventually shows the myDiv content and also button’s value changed to ‘Hide’. To achieve this functionality we’re doing several things as outlined below for clarity.
- We’re binding click event to the button toggle.
- In the click event (or when user clicks the button) we’re retrieving the CSS display property of myDiv. Essentially, the display property controls the visibility of an HTML element.
- Based on the display property whether its block or none we’re hiding or showing the myDiv respectively. At the same time we’re also updating button’s value for better usability.
This simple example demonstrates the power of jQuery and the control it has over DOM tree and its full fledged event handling mechanism.
- The official jQuery website is http://jquery.com/
- Latest version of jQuery can be downloaded from http://jquery.com/download/
- jQuery documentation can be referred from http://api.jquery.com/