Events

These methods are used to register behaviors to take effect when the user interacts with the browser, and to further manipulate those registered behaviors.

on

Attach an event handler function for one or more events to the selected elements.

Attach an event handler

jQuery

element.on('click', function() {
    alert('Hello!');
});

Vanilla JS

element.addEventListener('click', function() {
    alert('Hello!');
});

Attach single handler to multiple events

jQuery

$(element).on('mousedown mouseup', function(event) {
    console.log(event.type);
});

Vanilla JS

['mousedown', 'mouseup'].forEach(function(type) {
    element.addEventListener(type, function(event) {
        console.log(event.type);
    });
});

Delegate event

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

jQuery

element.on('click', '.hello', function() {
    alert('Hello!');
});

Vanilla JS

element.addEventListener('click', function(event) {
    if (event.target.matches('.hello')) {
        alert('Hello!');
        event.stopPropagation();
    }
});

off

Remove an event handler.

jQuery

element.off('click', handler);

Vanilla JS

element.removeEventListener('click', handler);

one

Attach a handler to an event for the elements. The handler is executed at most once per element.

jQuery

element.one('click', function() {
    alert('Hello!');
});

Vanilla JS

element.addEventListener('click', function(event) {
    alert('Hello!');
    event.target.removeEventListener(event.type, arguments.callee);
});

trigger

Execute all handlers attached to the matched elements for the given event type.

jQuery

element.trigger('click');

Vanilla JS

element.dispatchEvent(new Event('click'));    
shopify traffic stats