Event Handling Using JQuery

Event Handling Using JQuery

JQuery is one of the most popular JavaScript libraries used by web developers, it presents an easier way to write JavaScript by offering much shorter syntaxes compared to those of pure JavaScript.

In this article, we're going to cover one of the most important topics in web development "Event Handling" and how to do it using JQuery.

Prerequisites

  • A solid understanding of HTML.

  • A decent understanding of JavaScript.

  • A basic understanding of JQuery

UNDERSTANDING EVENTS

What are events?

Events are the actions of a user as they browse through a website, is the user currently scrolling? or filling out a form? did they click on a link? etc.

Event handling is the act of writing code that watches for these situations and instructs the web page to respond a certain way whenever a certain event takes place. For example, let's say you want a form to suddenly appear somewhere on your page when users click on a particular link, you can write an event handler to handle that.

Types of events

Events are categorized into 6 major categories namely;

  1. UI Events

  2. keyboard Events

  3. Mouse Events

  4. Focus Events

  5. Form Events

  6. Mutation Events

UI Events

UI events are also called browser events, they are the events that result from users' interactions with the browser and not necessarily the site itself, for example, when a user resizes the browser window.

Here are the events categorized under UI events.

EVENTDESCRIPTION
loadThe web page has finished loading
unloadThe web page is unloading (usually because the user has requested a new page before the current one finished loading)
errorThe browser encounters a JavaScript error
resizeThe browser window has been resized
scrollThe user scrolls

Keyboard Events

These are the events that result from changes that users make by typing.

Here are the events under this category.

EVENTDESCRIPTION
keydownThe user presses a key
keyupThe user releases a key
keypressThe user presses a key

Mouse Events

These are the events that result from what the user does with their mouse at every point in time.

Here are the events under this category.

EVENTDESCRIPTION
clickThe user clicks on an element
dblclickThe user double-clicks an element
mousedownThe user presses down the left-click button over an element
mouseupThe user releases the left-click button over an element
mousemoveThe user moves the mouse (not available on touchscreen devices)
mouseoverThe user moves the cursor over an element (not available on touchscreen devices)
mouseoutThe user moves the cursor away from the position of an element (not available on touchscreen devices)

Focus Events

These are the events that represent times when an element gains focus or loses it, for example, when you click on a textbox and it shows that it is ready to receive your text input, then the textbox has just gained focus, and when you click on another element thereby leaving the textbox, then it has just lost it.

Here are the events in this category.

EVENTDESCRIPTION
focusAn element has gained focus
blurAn element has lost focus

Form Events

These are the events that result from how a user interacts with a form.

Here are the events in this category.

EVENTDESCRIPTION
inputA new character has been entered into an <input> or <textarea> element
changeThe value in a select box, a check box or a radio button has changed (when checked or unchecked)
submitThe user submits the form
resetThe user clicks on the form's reset button
cutThe user cuts content from the form field
copyThe user copies content from the form field
pasteThe user pastes content into the form field
selectThe user selects some text in the form field

Mutation Events

These are the events that result from the modifications made to the DOM tree.

Here are the events under this category.

EVENTDESCRIPTION
DOMSubtreeModifiedThe DOM has been modified
DOMNodeInsertedA node has been added to the DOM as a child
DOMNodeRemovedA node has been removed from the DOM

WRITING EVENT HANDLERS

To write a valid event handler, 3 kinds of information must be provided in the syntax, in this order:

  • The element you're writing the event handler for.

  • The event you want to respond to.

  • A function that contains the response you want to send when the event happens.

The syntax

This is the JQuery syntax for a valid event handler.

$('element').on('event', function)

Practical example

Let's say this is the HTML code your script is connected to...

<html>
    <head><title>Random Form</title></head>
    <body>
        <form action="">
            <label for="username">username</label>
            <input type="text" id="usname">
            <br>
            <label for="password">password: </label>
            <input type="text" id="psword">
            <br>
            <input type="submit" id="submitbtn">
        </form>
        <div id="warning"></div>
    </body>
</html>

and you want to write an event handler that checks if the characters in the username textbox are up to 5 and also displays a warning message to the user if the characters aren't up to 5, this is an event handler to handle this situation:

// this gets the element that will hold the warning message
var warning = $('div#warning')

// the event handler
$('input#usname').on('input', function(){
    // checks the number of characters everytime there's a new input
    if (($(this).val().length) < 5){
        // displays warning message if the characters < 5
        warning.text('the username must have at least 5 characters')
    }else{
        // clears warning message if the characters are up to 5
        warning.text('')
    }
})

Result

Before reaching 5 characters:

After reaching 5 characters:

Another way to write event handlers

Some developers don't like to write their function inside the event handler, so instead they write the function separately and then call it inside the event handler, code example...

var warning = $('div#warning')

// the function
function warnMessage(){
    if (($(this).val().length) < 5){
        warning.text('the username must have at least 5 characters')
    }else{
        warning.text('')
    }
}

// the event handler
$('input#usname').on('input', warnMessage)

This example does the exact same thing as the earlier one, but this time we didn't write the function inside the event handler, instead, we wrote a function named warnMessage() then we called it inside the event handler.

CONCLUSION

Now that you have learned about events and how to respond to them using JQuery, the next step is to get on your computer and start practicing with different types of events, reading an article isn't enough, we learn by doing.

That would be all for this article, I appreciate you for reading this far ❤️, if you don't already follow me, please do 🙏.

Thank you, catch you on the next one ✌️.