jQuery Demo

Requirements:

Include jQuery library with: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> in head of document

Selectors

In CSS you target elements like this:

sometag { css properties.. }

.someclass { css properties.. }

#someid { css properties.. }

In jQuery you use the following syntax:

$('sometag')

$('.someclass')

$('#someid')

When referencing a jQery object from the element itself you can also use $(this)

This creates a jQuery object that can utilize functions from the jQuery library, see below.

Adding, Removing and checking for Classes

To add a CSS class to an element use the addClass method like so:

$('#someid').addClass('newclass');

Note that you DO NOT include the . when adding the class - just the class name. In this case we added a class of "newclass" to #someid

Removing classes is very similar:

$('#someid').removeClass('oldclass');

In this case we removed a class of "oldclass" to #someid

Now to check if an element has a class already we use the hasClass method which returns true or false and needs to be part of an if statement like so

if($('#someid').hasClass('oldclass')){

     // returned true so do something..

}

Putting it all together

 

In order to call a method on a jQuery element or any function, we need an event. We can specify many events including:

click, mouseover, mouseout, mouseenter, mouseleave, mousemove, etc..

You can set an event listener a few different ways here are the most basic methods:

OPTION 1: Inline on the element itself

<p onclick="$(this).addClass('newclass');">Click me and see what happens</p>

NOTE: the use of $(this) because we are interacting with the same element we are changing

OPTION 2: On Document Ready

Using the jQuery ready method you can set all your event listeners at once. It also allows all the code to be managed in a single place VS inline method

$(document).ready(function(){

     $('p').click(function(){ $(this).addClass('newclass'); });

     $('h1').click(function(){ $(this).removeClass('oldclass'); });

      $('h1').click(function(){

           if($(this).hasClass('oldclass')){

                 $(this).removeClass('oldclass');

           }

     });

});