Week 9:

jQuery Events



Event Handlers

There are a number of different ways to add events to HTML objects using jQuery. These naturally replace function calls to addEventListener() and hopefully streamline your code a bit more. There are different methods for different kinds of interactions:

Click this.
Hover over this.
Mouseover this.
Mouseout from this.

$("#click").click(function(){
    $(this).toggleClass("funkystyles");
});
$("#hover").hover(function(){
    $(this).toggleClass("funkystyles");
});
$("#mouseover").mouseover(function(){
    $(this).toggleClass("funkystyles");
});
$("#mouseout").mouseout(function(){
    $(this).toggleClass("funkystyles");
});

This same effect can be achieved by using the on() method which behaves very similarly to addEventListener() by taking in an argument to identify what kind of interaction it should respond to.

Click this.
Hover over this.
Mouseover this.
Mouseout from this.

$("#onclick").on("click", function(){
    $(this).toggleClass("funkystyles");
});
$("#onhover").on("mouseenter mouseleave", function(){
    $(this).toggleClass("funkystyles");
});
$("#onmouseover").on("mouseover", function(){
    $(this).toggleClass("funkystyles");
});
$("#onmouseout").on("mouseout", function(){
    $(this).toggleClass("funkystyles");
});

We can use the on() method to add multiple different events simultaneously by constructing them inside of a JavaScript object.

This div will respond when your mouse cursor goes over it, leaves it, as well as when you click on it.

$("#mult").on({
    mouseenter: function(){
        $(this).css("background-color", "blueviolet");
    },
    mouseleave: function(){
        $(this).css("background-color", "#f99");
    },
    click: function(){
        $(this).css("background-color", "#090");
    }
});

Editing Properties of Objects

HTML elements can have their attributes, CSS styles, and their inner HTML modified dynamically. This works a little different than when we use document.querySelector() to get a reference to an HTML element.

Change attribute.

Change CSS.
Change HTML.
Get a custom attribute.

$("#attr").on("click", function(){
    $("#tacos").attr("src", "../week7/tacos2.jpg");
});
$("#css").on("click", function(){
    $(this).css("background-color", "#666");
});
$("#html").on("click", function(){
    $(this).html("Let's just take over this div right here...");
});
$("#getattr").on("click", function(){
    var content = $(this).attr("imadethisattrup");
    $(this).html(content);
});

Resources