user2026796222222222
user2026796222222222

Reputation: 81

Event triggers multiple times

$("input[type='color']").on("change blur", function() {
    alert("changed");
});

This also applies to other elements, but this is a good example. When using a colour input type on some browsers it triggers on 'change' but not on 'blur', on some it triggers on 'blur', but not on 'change' and some it triggers on both.

Is there a good method to ensure it only triggers once?

I'm mainly talking about various mobile browsers here.

Upvotes: 1

Views: 288

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173652

I've written a specialized version of .one() that will rebind the event handlers after the first event has been handled. It does this in a wrapper so that the event handler code itself doesn't have to be changed.

$.fn.one_rebind = function(events, listener) {
  return this.one(events, function fn() {
    var $self = $(this).unbind(events);

    listener.apply(this, arguments);

    setTimeout(function() {
      $self.one(events, fn);
    }, 0);
  });
};

$('input[type=color]').one_rebind('change blur', function(evt) {
  document.getElementById('debug').innerText += ' ' + evt.type;
});

Although tested, your mileage may vary :)

Demo

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Start your function with this:

var now = new Date().getTime();
if( arguments.callee.lastcalled > now-250) return false;
arguments.callee.lastcalled = now;

What this does is limit the function from being called more than once every 250 milliseconds (which is usually enough without risking missing actual duplicates)

Upvotes: 0

ferne97
ferne97

Reputation: 1073

You can try the .one() event handler instead of .on() http://api.jquery.com/one/

Upvotes: 3

Related Questions