multiple first evitar doble deshabilitar dbclick avoid jquery double-click

evitar - on first click jquery



¿Cómo evitar un doble clic con jQuery? (13)

Tengo un botón como tal:

<input type="submit" id="submit" value="Save" />

Dentro de jQuery estoy usando lo siguiente, pero todavía permite hacer doble clic:

<script type="text/javascript"> $(document).ready(function () { $("#submit").one(''click'', function (event) {

¿Alguna idea de cómo puedo evitar hacer doble clic?


Descubrí que la mayoría de las soluciones no funcionaban con clics en elementos como etiquetas o DIV (por ejemplo, al usar los controles de Kendo). Así que hice esta solución simple:

function isDoubleClicked(element) { //if already clicked return TRUE to indicate this click is not allowed if (element.data("isclicked")) return true; //mark as clicked for 1 second element.data("isclicked", true); setTimeout(function () { element.removeData("isclicked"); }, 1000); //return FALSE to indicate this click was allowed return false; }

Úselo en el lugar donde tiene que decidir si desea iniciar un evento o no:

$(''#button'').on("click", function () { if (isDoubleClicked($(this))) return; ..continue... });



Este es mi primer post y soy muy inexperto, así que, por favor, sea fácil, pero creo que tengo una contribución válida que puede ser útil para alguien ...

A veces, se necesita una ventana de tiempo muy grande entre los clics repetidos (por ejemplo, un enlace de correo electrónico a donde la aplicación de correo electrónico tarda un par de segundos en abrirse y no quiere que se vuelva a activar), pero no quiere reducir la velocidad. usuario abajo en otro lado. Mi solución es utilizar los nombres de clase para los enlaces según el tipo de evento, mientras se conserva la funcionalidad de doble clic en otra parte ...

var controlspeed = 0; $(document).on(''click'',''a'',function (event) { eventtype = this.className; controlspeed ++; if (eventtype == "eg-class01") { speedlimit = 3000; } else if (eventtype == "eg-class02") { speedlimit = 500; } else { speedlimit = 0; } setTimeout(function() { controlspeed = 0; },speedlimit); if (controlspeed > 1) { event.preventDefault(); return; } else { (usual onclick code goes here) } });


La solución provista por @Kichrum casi me funcionó. Tuve que agregar e.stopImmediatePropagation () también para evitar la acción predeterminada. Aquí está mi código:

$(''a, button'').on(''click'', function (e) { var $link = $(e.target); if (!$link.data(''lockedAt'')) { $link.data(''lockedAt'', +new Date()); } else if (+new Date() - $link.data(''lockedAt'') > 500) { $link.data(''lockedAt'', +new Date()); } else { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); } });


Lo que descubrí era una solución antigua pero funcional en navegadores modernos. Funciona para no alternar clases en el doble clic.

$(''*'').click(function(event) { if(!event.detail || event.detail==1){//activate on first click only to avoid hiding again on double clicks // Toggle classes and do functions here $(this).slideToggle(); } });


Mi solución: https://gist.github.com/pangui/86b5e0610b53ddf28f94 Evita el doble clic pero acepta más clics después de 1 segundo. Espero eso ayude.

Aquí está el código:

jQuery.fn.preventDoubleClick = function() { $(this).on(''click'', function(e){ var $el = $(this); if($el.data(''clicked'')){ // Previously clicked, stop actions e.preventDefault(); e.stopPropagation(); }else{ // Mark to ignore next click $el.data(''clicked'', true); // Unmark after 1 second window.setTimeout(function(){ $el.removeData(''clicked''); }, 1000) } }); return this; };


Solo una solución más:

$(''a'').on(''click'', function(e){ var $link = $(e.target); e.preventDefault(); if(!$link.data(''lockedAt'') || +new Date() - $link.data(''lockedAt'') > 300) { doSomething(); } $link.data(''lockedAt'', +new Date()); });

Aquí guardamos el tiempo del último clic como atributo de datos y luego verificamos si el clic anterior fue hace más de 0,3 segundos. Si es falso (hace menos de 0,3 segundos), actualice el tiempo de último clic, si es verdadero, haga algo.

jsbin


Tengo el mismo problema. Puedes usar setTimeout () para evitar hacer doble clic.

//some codes here above after the click then disable it

// también marque aquí si hay un atributo deshabilitado

// si hay un atributo deshabilitado en la etiqueta btn, entonces // devolver Convertir eso en js.

$(''#btn1'').prop("disabled", true); setTimeout(function(){ $(''#btn1'').prop("disabled", false); }, 300);


Tuve un problema similar, pero deshabilitar el botón no funcionó del todo. Hubo algunas otras acciones que tuvieron lugar cuando se hizo clic en el botón y, a veces, el botón no se desactivó lo suficientemente pronto y cuando el usuario hizo doble clic, se activaron 2 eventos.
Tomé la idea del tiempo de espera de Pangui, y combiné ambas técnicas, deshabilitando el botón e incluí un tiempo de espera, por si acaso. Y creé un complemento simple de jQuery:

var SINGLECLICK_CLICKED = ''singleClickClicked''; $.fn.singleClick = function () { var fncHandler; var eventData; var fncSingleClick = function (ev) { var $this = $(this); if (($this.data(SINGLECLICK_CLICKED)) || ($this.prop(''disabled''))) { ev.preventDefault(); ev.stopPropagation(); } else { $this.data(SINGLECLICK_CLICKED, true); window.setTimeout(function () { $this.removeData(SINGLECLICK_CLICKED); }, 1500); if ($.isFunction(fncHandler)) { fncHandler.apply(this, arguments); } } } switch (arguments.length) { case 0: return this.click(); case 1: fncHandler = arguments[0]; this.click(fncSingleClick); break; case 2: eventData = arguments[0]; fncHandler = arguments[1]; this.click(eventData, fncSingleClick); break; } return this; }

Y luego úsalo así:

$("#button1").singleClick(function () { $(this).prop(''disabled'', true); //... $(this).prop(''disabled'', false); })


solo coloque este método en sus formularios, entonces manejará el doble clic o más clics una vez. Una vez enviada la solicitud no se permitirá enviar una y otra vez.

<script type="text/javascript"> $(document).ready(function(){ $("form").submit(function() { $(this).submit(function() { return false; }); return true; }); }); </script>

Te ayudará con seguridad.


one() jQuery activará el controlador de eventos adjunto una vez por cada elemento enlazado y luego eliminará el controlador de eventos.

Si por algún motivo no cumple con los requisitos, también se puede desactivar el botón por completo después de hacer clic.

$(document).ready(function () { $("#submit").one(''click'', function (event) { event.preventDefault(); //do something $(this).prop(''disabled'', true); }); });

Se debe tener en cuenta que el uso del submit ID puede causar problemas, ya que sobrescribe la función form.submit con una referencia a ese elemento.


"Pan comido"

$(function() { $(''.targetClass'').dblclick(false); });


/* Double click behaves as one single click "It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable." That way we have to check what is the event that is being executed at any sequence. */ var totalClicks = 1; $(''#elementId'').on(''click dblclick'', function (e) { if (e.type == "dblclick") { console.log("e.type1: " + e.type); return; } else if (e.type == "click") { if (totalClicks > 1) { console.log("e.type2: " + e.type); totalClicks = 1; return; } else { console.log("e.type3: " + e.type); ++totalClicks; } //execute the code you want to execute } });