Basic jQuery events

This post is about some basic jQuery events. We study the dblclick event (occurs when an element is double-clicked), the hover event (occurs when the mouse pointer is over the element), and the focus event ( occurs when an element is in focus).

The dblclick event

The dblclick event occurs when an element is double-clicked. The dblclick() method triggers the dblclick event, or attaches a function to run when a dblclick event occurs.

$(selector).dblclick(function(){});

The hover event

The .hover() method triggers both the mouseenter and mouseleave events.

$(selector).hover(inFunction,outFunction);

The first parameter is required. It specifies the function to run when the mouseenter event occurs. The second one is optional. Specifies the function to run when the mouseleave event occurs.

hover me
<div class="fancy-butt">hover me</div>

<script>
    $('.fancy-butt').hover(
        function(){
            $(this).addClass('active');
        },
        function(){
            $(this).removeClass('active');
        }
    );
</script>

The .focus() method

An element has focus when we click on it or tab over to it. The focus() method triggers the focus event, or attaches a function to run when a focus event occurs.

$(selector).focus(function)

The .focus() method only works on elements that can receive focus (e.g. input or textarea).

$('.focus-input').focus(function(){
    var orig = $(".focus-input").css('background');
    $(".focus-input").data('orig-background', orig);       
    $('.focus-input').css('background','#444');
});

$('.focus-input').focusout(function(){
    var orig = $(".focus-input").data('orig-background');
    $(".focus-input").css('background', orig);
});

Sources

(1) Codecademy

(2) w3Schools


comments powered by Disqus