JQuery 101: Your First JQuery Script
Jquery Coding Preparation
If you have not already done so, download the JQuery library from www.jquery.org and make sure that you put the .js file in the same directory where you create your HTML document, or the browser will not be able to find it. Invoke your text editor of choice, or IDE, and start a new document. For this example, if you have not downloaded a fancy text editor or IDE, feel free to use Notepad in Windows or gEdit in Linux to write your first document as it will be easy to keep track of the syntax. You can refer to this page as a reference as you go.
Creating an HTML document
Before we can insert any JQuery code, we must first have an HTML file to go around it. In your text editor, enter the following HTML code:
<HTML> <HEAD> <TITLE>Welcome to JQuery </HEAD> <BODY> This is HTML. </BODY> </HTML>
At this point, we haven’t used any JQuery. Save the file as jquery.html, in the same directory where you downloaded the JQuery library. In your browser, select File -> Open -> Browse… and browse to your jquery.html document. The file should open and “This is HTML” should appear in your browser window.
Adding JQuery to Your HTML Document
Next, we are going to add the standard snippets of code that must be present to make the browser interpret your script as JQuery. In your jquery.html file, add the following lines at the very top:
This is called a directive and lets the browser know that the document contains script, so watch out for it and don’t type it as plain text. Without it, the browser would just type your script out as if it were part of the document.
Next, we add some text to our document between thetags, after “This is HTML.”
We need one more set of tags to complete our first program, right before the </body>tag:
<div id=”jquery”> </div>
Our completed Welcome to JQuery document looks like this all together:
This is your completed HTML/JQuery file. Once you save it, you can again open it in your web browser. Two lines of text should appear, one in HTML, one in JQuery. Obviously, there is far more that you can do with the language than simply write a message, but it is important to see the basic structure of how it is set up. At the beginning, we tell the browser to expect script. We then call the script out in the body of the document using <script> tags, then we use the <div> tags to insert our script at a certain point.
This creates a dynamic HTML file inside a static HTML document that is accessed by the browser and inserted in the space created by the <div> tags. JQuery can create dynamic content and the content of the page can change without navigating away from the page, but only the scripted part. The static part of the HTML document will remain the same regardless of the script.
Next, we will discuss the best practices for using JQuery.