jQuery For Complete Beginners

jQuery For Complete Beginners – Click, Hover And ToggleClass Events

Knowing how to select an element on the page is great, but even more exciting is learning how to do something with it.

In this post we’ll cover exactly that.

This post is a part of jQuery For Complete Beginners Series
Learn everything you need to know about jQuery before you can create awesome interactive websites using GreenSock or ScrollMagic.
1. Datatypes and Selectors
2. Click, Hover And ToggleClass Events
3. Console.log(), scrollTop(), resize()
4. Custom Functions, If Statement

What you’ll learn today:

  • How to use a click event
  • How to use a hover event
  • How to toggle a css class

Click Events

jQuery For Complete Beginners

The simplest way of interacting with HTML elements is the Click Event.

You click on something (e.g. a selected element), and something will happen.

The click event in jQuery works like this:

$("#target").on( "click", function() {
	alert("I hate tomatoes.");
});

If you’ve already declared a variable at the top of the page, you can refer to this variable instead of writing the selector.


// declare a variables first
var $clickMeElement = $('#gallery li').eq(0);

// use this variable
$clickMeElement.on( "click", function() {
	alert("I hate tomatoes.");
});

This will trigger a javascript alert when the user clicks on the first image in the #gallery.

Hover Events

jQuery For Complete Beginners

Another event we all encounter hundreds of times a day is hover.

If you mouse-over something (e.g. a selected element) and something will happen, you can then mouse-off and something else can happen.

The hover event in jQuery works like this:


// declare a variables first
var $hoverMeElement = $('#gallery li').eq(1);

// use this variable
$hoverMeElement.hover(
	function() {
		$(this).css('transform','rotate(90deg)');
	}, function() {
		$(this).css('transform','rotate(0)');
	}
);

This will rotate the second image in the #gallery 90deg on mouseenter and back to 0deg on mouseleave.

Toggle A CSS Class On Click

jQuery For Complete Beginners

Another very commonly used event on interactive websites is toggleClass.

You do something and jQuery will add or remove a class from a specified element.

The toggleClass event in jQuery works like this:


// declare a variables first
var $toggleTrigger = $('#gallery li').eq(-1);

// use this variable
$toggleTrigger.click(function() {
  $(this).toggleClass("highlight");
});

This will add .highlight to the last item in the #gallery.

Playground

jQuery For Complete Beginners

Use the following CodePen demo to play with click, hover and toggleClass events.

I’ve also included the animate.css library so you can go crazy and experiment especially with the toggleClass event.

4864

Adding and removing CSS classes is a very common approach especially when you are working with CSS animation libraries.

Conclusion

Now you know how to select the right element on a page and how to add some basic interaction using a few events.

To explore the rest of the available events visit jQuery documentation.

And let me know in the comments below what else are you struggling with when it comes to understanding JavaScript or jQuery.

In the next article you’ll learn:

  • how to alert a message
  • how to use browser console
  • how to debug JavaScript errors
  • how to get page top offset on scroll
  • how to get window width on resize

console.log, scrollTop, resize

10 thoughts on “jQuery For Complete Beginners – Click, Hover And ToggleClass Events

  1. hemant

    hi Petr Tichy
    i am looking for a action when i hover my cursor on a div tag then it will be auto clicked can you give me some code for this or guide me
    I will be highly obeliezed to you.

    Reply
  2. Tom Hartney

    Hi Petr
    noob question –
    Just wondering why you name some of your variables starting with $ – so $varName or similar.
    I was reading that it can be an indicator to say this variable stores a jQuery value?
    Is that something we should do as best practice? and name all other variables without the $ to help differentiate?
    Thanks

    Reply
    1. Petr Tichy Post author

      Hi Tom, I usually use the $varName for DOM objects on the page and a simple varName for any other variables.

      In practice, this is how I would create my variables.

      var $emailField = $("input#emailField");
      var email = $("input#emailField").val();
      

      The first one is selecting the email field HTML element, the second is holding the value of the input.

      Hope that makes sense, but feel free to name your variables however you like, this is just my own preference.

      Reply
  3. Lina

    Hi Petr,

    I also have a noob question – what is the function of an empty function? What is the added value of “function()” in your code

    $('a').hover(
        function() {
            $(this).trigger('click');
        }, function() {
          event.preventDefault();
        }
    );
    [javascript]
    
    and why isn't it just something like this?
    
    [javascript]
    $('a').hover( 
        {
            $(this).trigger('click');
        },{
          event.preventDefault();
        }
    );
    
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.