Profile photo of Travis Horn Travis Horn

Simple jQuery

2016-08-04
Simple jQuery

This post is part of a project to move my old reference material to my blog. Before 2012, when I accessed the same pieces of code or general information multiple times, I would write a quick HTML page for my own reference and put it on a personal site. Later, I published these pages online. Some of the pages still get used and now I want to make them available on my blog.

jQuery is a fast, concise, JavaScript library that simplifies how to traverse HTML documents, handle events, perform animations, and add AJAX.

Including it in a Page

The simplest method is to use the jQuery CDN and include jQuery just before the closing </body> tag.

<!doctype html>
<html>
  <head>
    <title>[TITLE]</title>
  </head>
  <body>
    [CONTENT]

  <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script>
      $(function() {
        // Put your jQuery code here.
      }
    </script>
  </body>
</html>

Selecting Elements

Most methods in jQuery require you to target an element(s) on the page.

This selects all <p> elements:

$('p').doSomething();

Select an element that has the id target. For example <div id="target">:

$('#target').doSomething();

Select all elements with the class selectme. For example <div class="selectme"> or <li class="selectme">:

$('.selectme').doSomething();

For more information about selecting elements, visit https://api.jquery.com/category/selectors/.

Manipulating Selected Elements

In all three of the examples above, the method being called was doSomething(). There’s no such method as doSomething() in the default jQuery library, but here are some real ones you can use.

Add the class highlight to every <span> on the page:

$('span').addClass('highlight');

Set the HTML inside every <p> to Replacement text.

$('p').html('Replacement text.');

Changes the alt attribute of <img id="header" …> to Sky with clouds:

$('img#header').attr('alt', 'Sky with clouds');

For more information about manipulation, visit https://api.jquery.com/category/manipulation/.

Events

Events are a way to perform an action when a condition is met. Some examples follow.

Executes when the user clicks on target:

$('#target').click(function() {
  // Do something.
});

Executes when the user hovers over target:

$('#target').hover(function() {
  // Do something.
});

Executes when target gains focus (user clicks or tabs into it):

$('#target').focus(function() {
  // Do something.
});

Learn more about events at https://api.jquery.com/category/events/.

Cover photo by Charlie Harutaka.

Here are some more articles you might like: