DEV Community

Cover image for jQuery Introduction Tutorial
Richard Rembert
Richard Rembert

Posted on • Updated on

jQuery Introduction Tutorial

We’ll be taking a brief look at the state of jQuery in this article. For those interested in learning a bit about it, we’ll run through the basics — including element manipulation, events, and effects. We’ll finish up with some useful examples showing jQuery in action.

What is jQuery?

jQuery is a DOM manipulation library that essentially helps us do many JavaScript tasks much faster and more simply.

It comes with a number of useful methods for:

  • Selecting/Manipulating/Creating Elements
  • Adding Event Listeners
  • Animating Elements
  • Adding Effects
  • Making HTTP Requests (AJAX)

Why Use jQuery?

  • It’s easy to learn and use
  • Makes DOM manipulation a breeze
  • Has cross-browser support
  • Working with AJAX is easy
  • Lots of knowledge out there if you need help

If you don’t already know jQuery, is it worth learning today?

Some projects may be using libraries such as Bootstrap, which for the time being has a dependency on jQuery. As do some ready-made templates. Some developer teams are comfortable working with jQuery and that’s fine too.

In these cases, jQuery remains relevant. Also, if you’re looking to secure your first developer job, many companies still use jQuery. So knowing a bit about it would be a good idea!

Using jQuery

So assuming you want to learn some jQuery, let’s get started!

Create a demo project

We’ll begin by creating a demo project. Add a style.css in a css/directory, a scripts.js in a js/ directory, and a main index.html in the root directory of the project.

Setting up jQuery

jQuery is simply a JavaScript file that you’ll link to in your HTML. There are two ways to include it in your project:

Let's open our index.html, and copy in the following code:

Note: We will be working with these elements <h1>, <ul>, <img>, <div>, later on in this article — so copy it all in now to save time!

<!doctype html>
<html lang="en">

<head>
  <title>jQuery Demo</title>
  <link rel="stylesheet" href="css/style.css">
</head>

<body>
  <h1 id="demo"></h1>
  <ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li> 
  </ul>
  <img src="https://upload.wikimedia.org/wikipedia/commons/d/d3/Logo_jQuery.svg" width="300px">
<div>
    <button id="submit">Click me</button>
    <input type="text">
</div>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script src="js/scripts.js" />
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

And make sure you place the script tags just before the</body> tag, ensuring scripts.js is placed after your jQuery script — or it won’t work!

Now open up scripts.js and add the following:

$(document).ready(function() {
    // All your jQuery will go here!
});
Enter fullscreen mode Exit fullscreen mode

We do this as in order to manipulate a page with jQuery, we need to ensure the document is “ready” first. All the code we write will need to be wrapped in this code (it’s best practice).

Let's see it in action with a quick demo! Add the following line to your scripts.js

$(document).ready(function() {
    $("#demo").html("This text is brought to you by jQuery!");
});
Enter fullscreen mode Exit fullscreen mode

If you open up index.html you'll see the text has been added to the h1 element via jQuery!

Selecting with jQuery

To begin, we call jQuery with the dollar sign$. We access the DOM using mostly CSS syntax, and apply an action using a method. The basic syntax is like so:

$("selector").method();
Enter fullscreen mode Exit fullscreen mode

Selectors are essentially how we tell jQuery which elements we want to work on. Let's look at a few of the ways we can select elements (see the complete list).

// Select all image tags
$("img")

// Select all elements with the 'social' class
$(".social")

// Select all elements with the 'social' id
$("#social")

// Select all <a> tags inside of <li>'s
$("li a")

// Selects the current element being used within a function
$(this)
Enter fullscreen mode Exit fullscreen mode

Now go and have a play around in the browser! Open your index.html and practice selecting elements in your browser console. For example, running $(“h1”) will display your <h1>. You could even change its color with $(“h1”).css("color", "yellow"); See the full list of CSS manipulations here.

jQuery Methods

Let's now take a look at a few of the more common jQuery methods in action.

text()

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

Running $(“h1”).text() in your console will output “This text is brought to you by jQuery!” which is the text content of our <h1>. We can change this text by passing in new text, such as$(“h1”).text("Time for a new heading!")

html()

Get the HTML content of the first element in the set of matched elements or the set of HTML contents of every matched element.

Let's ask for the HTML of our <ul> element with $(“ul”).html(), this will retrieve our inner HTML: <li>First</li> <li>Second</li> <li>Third</li>.And we can change it by passing in the new HTML, for example $(“ul”).html("<li>Your</li> <li>New</li> <li>List items</li>")

attr()

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

Let's work with the <img> in our HTML. We can retrieve its source with $(‘img’).attr(“src”); and we can replace it with a new image, with $(‘img’).attr(“src”,“https://upload.wikimedia.org/wikipedia/commons/1/1c/Logo_Rad.jpg");

Class Manipulation

The next 3 methods will be looking at how we manipulate classes on our page. Open up the style.css we created earlier and add the following:

.green {
  color: green;
}

.red {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

addClass()

Adds the specified class(es) to each element in the set of matched elements.

We can add our green class to the first item in our list with $(“li:first-of-type”).addClass(“green”); If we now inspect our element we can see the class has been added to our HTML. If we wanted to add the class to all li’s, we’d simply say $(“li”).addClass(“green”);

removeClass()

Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

We can easily remove the class we just added to our first li with $(“li:first-of-type”).removeClass(“green”);

toggleClass()

Add or remove one or more classes from each element in the set of matched elements, depending on either the classes presence or the value of the state argument.

We can toggle a class like so $(“li”).toggleClass(“red”);Each time we run this code the class will toggle on and off, adding and then removing the styles we’ve included.

jQuery Event Methods

Next, we're going to take a look at a few examples of events — or, how we can make things interactive! See the complete list of event methods here.

click()

Bind an event handler to the “click” JavaScript event, or trigger that event on an element.

We can add a click event to our <button id="submit"> like so:

$("#submit").click(function() {
  alert("You clicked me!");
});
Enter fullscreen mode Exit fullscreen mode

When we click on the button we now get an alert stating “You clicked me!”.

keypress()

Bind an event handler to the “keypress” JavaScript event, or trigger that event on an element.

We can log keys which are pressed using this method. This is very handy for detecting when enter is pressed in an input field, for example:

$("input").keypress(function(event){
  console.log(event);
});
Enter fullscreen mode Exit fullscreen mode

What we’re doing here is listening for a keypress using the event and logging it to the console. Type any key into the input box & check out the event that it logs. You’ll see charCode, keyCode and which all have a unique number, which corresponds to the key you pressed. You can see the full list of character codes here. Let’s use which to detect when enter (its code is 13) is pressed:

$("input").keypress(function(event){
  if(event.which == 13){
    alert("You pressed enter!");
  }
});
Enter fullscreen mode Exit fullscreen mode

Now the alert event will fire when we press enter in our input box!

on()

Attach an event handler function for one or more events to the selected elements.

The on method works similarly to the pure js addEventListener, it lets you specify the type of event to listen for. It’s far and away the most used jQuery event method!

Let's look at an example of on using the click event:

$("li").on("click", function(){
  $(this).css("color", "green");
});
Enter fullscreen mode Exit fullscreen mode

Now when you click on any of the li’s it will change to green. We use $(this)as if we used $("li") it would change ALL li’s to green when one was selected!

Let's see another example, this time using mouseenter & mouseleave, remember you can use on() with any event.

$("h1").on("mouseenter", function(){
  $(this).css("text-decoration", "underline");
});

$("h1").on("mouseleave", function(){
  $(this).css("text-decoration", "none");
});
Enter fullscreen mode Exit fullscreen mode

Now when your mouse enters <h1>, it’ll underline. And when it leaves it’ll remove the underline.

on(‘click’) or click() ?

They will both get the job done, however there is one key difference.

  • click() only adds listeners to existing elements
  • on(‘click’) is much more dynamic, it’ll add listeners for all potential future elements

jQuery Effects

Effects work with events by allowing you to add animations and otherwise manipulate elements on the page. See the complete list of effects here.

fadeOut()

Hide the matched elements by fading them to transparent.

Let's use the following code to fade out our image:

$('img').on("click", function(){
  $(this).fadeOut(1000, function(){
    $(this).remove;
  });
});
Enter fullscreen mode Exit fullscreen mode

What is happening here? We have a callback function on our img which will use the fadeOut effect with a delay of 1000 (1 second). We then nest another callback function to remove the element once the fade-out has completed.

slideUp()

Hide the matched elements with a sliding motion.

$("button").click(function() {
  $("img").slideUp("slow");
});
Enter fullscreen mode Exit fullscreen mode

Now when we click on the button on our page, the image will ‘slide up’ out of view. The reverse of course is slideDown(), whilst slideToggle() will toggle between states.

jQuery Demos

Here are a few demos I’ve created showing jQuery in action:

Accordion

Drop Down

Simple Slider

Modal

Smooth Scroll

Tabs

Summary

And there you go! We've looked at how to select and manipulate elements with jQuery, and how we can work with events and effects to enhance user experience. We've also looked at a number of examples of jQuery in action - showing how simple it can be to get up and running, writing your own code!

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
Buy Me A Coffee If you enjoyed this article & would like to leave a tip — click here

🌎 Let's Connect

Top comments (1)

Collapse
 
decker67 profile image
decker

The time to use jQuery seems over, I would think.