.one()S2C Home « Events « .one()

One time only event handler attachment.

Description

The .one() method is used to attach an event handler for the given event type(s) that will execute a maximum of one times, optionally passing a selector and/or an object of data.

  • The .one() method is identical to the .on() method but will execute a maximum of one times and then unattach itself. Use the .on() method when you require mutiple event handler executions that stay attached.
  • See the description for the .on() method for details of jQuery eventing.

Syntax

Signature Description
.one( events [, selector] [, data], handler(eventObject) )Attach an event handler for the given String of event type(s), optionally passing a selector and/or an object of data.
.one( events [, selector] [, data] )Attach event handlers for the given PlainObject of event type(s), optionally passing a selector and/or an object of data.

Parameters

Parameter Description Type
eventsA String or PlainObject containing one or more DOM event types or custom event names.
  • If the String or PlainObject used for eventType is not the name of a native DOM event, the handler is bound to a custom event. Custom events are never called by the browser, but can be triggered manually from other JavaScript code using the .trigger() method.
  • If a period (.) character is present anywhere in the eventType string, then that event becomes namespaced. The characters before the period (.) character represent the eventType, whilst the characters after the period (.) character represent the namespace. As an example .on('anEventType.aNamespace', handler) could be used to handle some events whilst not affecting events for .on('anEventType.aNamespace2', handler). In essence, namespacing allows us to action certain events for an eventType without affecting other events for that eventType.
String or PlainObject
selectorA string containing a CSS or custom jQuery selector to filter the elements that trigger the events.
  • When the selector parameter is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether occuring directly on the element or bubbling up from a descendant element.
    • Event handlers are bound to the currently selected elements and therefore must exist on the page at the time the call to the .one() method is made. To ensure the elements are present and can be selected, perform event binding inside a document ready handler ( .ready() ) method for elements within the HTML markup on the page. For new HTML that is being created the page, select the elements and attach event handlers after the new HTML is present, or use delegated events to attach an event handler
  • When the selector parameter is present, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants matching the specifed selector parameter. jQuery bubbles the event from the event target up to the element where the handler is attached and runs the handler for any elements along that path matching the specifed selector parameter.
    • Delegated events have the advantage of being able to process events from descendant elements that are added to the document in the future. By selecting an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. The document element is available in the head of the document before loading any other HTML, so is a safe place to attach events without waiting for the document to be ready.
String
dataAn object or map of key-value pair data which can be any type. If this optional parameter is provided and is not null or undefined, it will be passed to the event handler via event.data property when the event occurs.
  1. If passing this parameter as a string the selector argument must be provided or explicitly passed as null so that the data argument is not mistaken for the selector argument.
  2. Where possible use an object (map) for this parameter so that multiple values can be passed as properties.
Anything
handler(eventObject)A function to execute each time the event is triggered or false.Function
eventsAn object of key-value pair data of event type(s) and handlers.PlainObject

Return

A jQuery object.

.one(events[,selector] [,data], handler(eventObject) ) ExamplesTop

Attach an event handler for the given String of event type(s) that will execute a maximum of one times ( direct event handler).

When we press the mouse button the click JavaScript event is fired and we output a message.


$(function(){
  $('#btn4').one('click', function(){
     $('#scrollspan1').append('** The JavaScript "click" event triggered for button **');
  });
});

Press the button below to action the above code:

We will show a message here for the mouse button presses.


Attach an event handler for the given String of event type(s) that will execute a maximum of one times, passing a selector ( delegated event handler).

When we press the mouse button the click JavaScript event is fired for the specified selector and we output a message.


$(function(){
  $('form').one('click', '#btn5', function(){
     $('#scrollspan2').append('** The JavaScript "click" event triggered for button **');
  });
});

Press the button below to action the above code:

We will show a message here for mouse button presses.


Attach an event handler for the given String of event type(s) that will execute a maximum of one times, passing a selector and an object of data ( delegated event handler).

In the next example we use all of the .one() methods parameters and pass an object of data to the addText() function, which outputs a message below.

What we are doing here is passing across the event object to the function addText(event). The object map we specify, in our case { param1: '#scrollspan3', param2: 'click was attached from .one()', param3: '**JavaScript event triggered** ' } gets tagged onto the Event.data property. We then access these parameter in the function via event.data.param and use it as part of the appended data.


$(function(){
  $('form').one('click', '#btn6',
                     { param1: '#scrollspan3', param2: 'click was attached from .one() ', 
                       param3: '**JavaScript event triggered**  ' }, addText);

  function addText(event) {
    $(event.data.param1).append(event.data.param2 + '<code>' + event.data.param3+ '</code>');
  }
});

Press the button below to action the above code:

We will show a message here.


In the next example we use all of the .one() methods parameters and pass a custom jQuery.Event object (ourEvent) to the addText() function, which outputs a message below.

What we are doing here is passing across our custom event object to the function addText(event). The parameters we specified for our custom event object get tagged onto the event.data property. We then access these parameters in the function and use it as part of the appended data.

This is a cleaner approach than passing a map of data as in the previous example. Imagine what the passed parameter code would look like when you were passing across many parameters. Also think about maintainability and how this approach makes maintaining the code much easier.


$(function(){
  var ourEvent = $.Event('click.ns1');
  ourEvent.param1 = '#scrollspan4';
  ourEvent.param2 = 'click was attached from .one() ';
  ourEvent.param3 = '**JavaScript event triggered** using custom object and namespace ';
  $('form').one('click.ns1', '#btn7', ourEvent, addText);

  function addText(event) {
    $(event.data.param1).append(event.data.param2 + '<code>' + event.data.param3+ '</code>');
  }
});

Press the button below to action the above code:

We will show a message here.


.on(events[,selector] [,data], handler(eventObject [, Anything extraParameter ] [, ... ] )Top

Attach a PlainObject of event type(s) and handlers that will execute a maximum of one times ( direct event handler).

In the example below when you press the left mouse button down or release the left mouse button while the cursor is over the 'div4' element the mousedown and mouseup JavaScript events fire once.


$(function(){
  $('#div4').one({
     'mousedown.ns4': function() {
       $(this).css({backgroundColor: 'orange', color: 'black'})
              .append('**mousedown "div4. "');
     },
     'mouseup.ns4': function() {
       $(this).css({backgroundColor: 'red', color: 'white'})
              .append('**mouseup "div4. "');
     }
  });
});

Some initial text.



Attach a PlainObject of event type(s) and handlers that will execute a maximum of one times, passing a selector ( delegated event handler).

In the example below when you press the left mouse button down or release the left mouse button while the cursor is over the 'para1' element the mousedown and mouseup JavaScript events fire once only. When this happens our custom event-types and their handlers are executed.


$(function(){
  $('#div5').one({'mousedown.ns5': ourHandler1}, '#para1');
  $('#div5').one({'mouseup.ns5': ourHandler2}, '#para1');

  function ourHandler1() {
    $(this).css({backgroundColor: 'yellow', color: 'black'})
           .append('**mousedown "div5. "');
  }
  function ourHandler2() {
    $(this).css({backgroundColor: 'teal', color: 'white'})
           .append('**mouseup "div5. "');
  }
});

para1. Some initial text.



Attach a PlainObject of event type(s) and handlers that will execute a maximum of one times, passing a selector and a map of data ( delegated event handler).

In the example when you press the left mouse button down or release the left mouse button while the cursor is over the 'para2' element the mousedown and mouseup JavaScript events fire once only. When this happens our custom event-types and their handlers are executed. The parameters we specified get tagged onto the event.data property. We then access these parameters in the function addTextand output a message.



$(function(){
  $('#div6').one({'mousedown.ns6': ourHandler3}, '#para2', 
                { param1: '#scrollspan5', param2: 'mousedown was attached from .one() ', 
                  param3: '**JavaScript event triggered**  ' });
  $('#div6').one({'mouseup.ns6': ourHandler4}, '#para2', 
                { param1: '#scrollspan5', param2: 'mouseup was attached from .one() ', 
                  param3: '**JavaScript event triggered**  ' });

  function ourHandler3(event) {
    $(this).css({backgroundColor: 'lime', color: 'black'})
           .append('**mousedown "div6. "');
    addText(event);
  }
  function ourHandler4(event) {
    $(this).css({backgroundColor: 'silver', color: 'white'})
           .append('**mouseup "div6. "');
    addText(event);
  }
 
  function addText(event) {
    $(event.data.param1).append(event.data.param2 + '' + event.data.param3 + '');
  }
});

para2. Some initial text.

We will show a message here.



In the example below when you press the left mouse button down or release the left mouse button while the cursor is over the 'para3' element the mousedown and mouseup JavaScript events fire once only. When this happens our custom event-types and their handlers are executed. We also pass a custom jQuery.event object (ourEvent2).

What we are doing here is passing across our custom event object to our handlers, which then gets passed to the addText(event) function. The parameters we specified for our custom event object get tagged onto the event.data property. We then access these parameters in the addText(event) function and use it as part of the appended data.

This is a cleaner approach than passing a map of data as in the previous example and makes code maintainance much easier.



$(function(){
  var ourEvent2 = $.Event('mousedown.ns7 mouseup.ns7');
  ourEvent2.param1 = '#scrollspan6';
  ourEvent2.param2 = 'events were attached from .one() ';
  ourEvent2.param3 = '**JavaScript event triggered** using custom object and namespace ';
  $('#div7').one({'mousedown.ns7': ourHandler5}, '#para3', ourEvent2);
  $('#div7').one({'mouseup.ns7': ourHandler6}, '#para3', ourEvent2);

  function ourHandler5(event) {
    $(this).css({backgroundColor: 'lime', color: 'black'})
           .append('**mousedown "div7. "'),
    addText(event);
  }
  function ourHandler6(event) {
    $(this).css({backgroundColor: 'red', color: 'white'})
           .append('**mouseup "div7. "');
    addText(event);
  }
 
  function addText(event) {
    $(event.data.param1).append(event.data.param2 + '' + event.data.param3 + '');
  }
});

para3. Some initial text.

We will show a message here.