Free Coding Bootcamp

where being self-taught is good for the soul

jQuery: Introduction

Using jQuery on your web page is pretty straignt forward. To implement jQuery:

  • Add a reference to the jquery.min.js file to your web page
  • Add your own code AFTER the reference to the jquery.min.js file
  • Be sure the first line of your code is: $(document).ready(function() {
  • Have the last line of your code be: });
  • Write your code using valid jQuery syntax
  • So your page loads faster, put your jQuery reference and your custom code AT THE END of your HTML file. Seeing that your code is read and rendered on to screens from top to bottom, images, text, etc. will load first ... and then your jQuery reference followed by your code.

So, with this in mind, let's get started.

Figure 1

Here is a simplified HTML file that uses jQuery pop an alert when any part of the paragraph is clicked on.

        <!doctype html>
        <html>
          <body>
          <p>Click on this paragraph and an alert box will pop up.</p>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
          <script>
          $(document).ready(function() {
            var txt = "I was clicked.";
            $('p').click(function() {
              alert(txt);
            });
          });
          </script>
        </body>
        </html>
            

Notice how I referenced the jQuery library in line 5 AND THEN implemented my own code in lines 6 - 13. And how all of these jQuery lines were added AFTER the paragraph tag<p>. as written in line 4.

Use this link to complete the exercises below: https://repl.it/I8bG

Lab Exercises:

  1. Customize what the alert says to something of your own
  2. Memorize the code so that you become intimate with the syntax

Memorization Exercise 1

Write out the opening and closing lines for a jQuery script. Don't forget the <script> tag!

Time Elapsed: 00:00:00

Line 1:

Line 2:

Line 3:

Line 4:

Let's review:

  1. We started off with standard HTML5 code
  2. Next, we added a reference to the jQuery library
  3. Finally, we added our own code
            
        <!doctype html>
        <html>
          <body>
            <p>Click on this paragraph and an alert box will pop up.</p>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
            <script>
              $(document).ready(function() {
                var txt = "I was clicked.";
                $('p').click(function() {
                  alert(txt);
                });
              });
            </script>
         </body>
        </html>
            

Here is the link you can use to create your own code: https://repl.it/I8bG