I've been binding events to dynamically created elements without any kind of issues by using:
$(document).on(event, element, function)
Now I want to bind a custom event and I just can´t get it to work.
The event is a JS plugin to handle single e double click. If I use it like this:
$('#test').oneordoubleclick({
oneclick: function () {
alert('you have clicked this node.');
},
dblclick: function () {
alert('you have double clicked this node.');
}
});
It works like a charm, but, as I transform the code to bind the event to dynamically created elements, like this:
$(document).on('oneordoubleclick', '#test', {
oneclick: function () {
alert('you have clicked this node.');
},
dblclick: function () {
alert('you have double clicked this node.');
}
});
It stops working!
It wasn't supposed to work? What am i doing wrong? It is possible to do what i want to accomplish?
According to my understanding, .oneordoubleclick is not an Event, just like .footable or .tooltip. Therefore, you cannot put it in $(document).on("oneordoubleclick","#test", ...)
Here's my solution, with the aid of the plugin source code:
// Custom functions
let singleClick = function () { // your function when is single click
alert('you have clicked this node.');
}
let doubleClick = function () { // your function when is double click
alert('you have double clicked this node.');
}
// Necessary to differentiate is single or double click
let timer,
do_click = function (e, fx) {
clearTimeout(timer);
timer = setTimeout(function () {
fx();
}, 400); // if there is no another click between 0.4s, then it is single click
},
do_dblclick = function (e, fx) {
clearTimeout(timer); // the single click function will not be called
fx();
};
// Listener
$(document) .on("click", "#test", function (e) { do_click(e, singleClick) })
.on("dblclick", "#test", function (e) { do_dblclick(e, doubleClick) })
Correct me if I'm wrong.
In addition to the correct answer, i needed to know which DOM element was responsible for the call. To achieve that i changed a little bit XH栩恒 answer code...
// Necessary to differentiate is single or double click
let timer,
do_click = function (e, fx, element) {
clearTimeout(timer);
timer = setTimeout(function () {
fx(element);
}, 400); // if there is no another click between 0.4s, then it is single click
},
do_dblclick = function (e, fx, element) {
clearTimeout(timer); // the single click function will not be called
fx(element);
};
// Listener
$(document).on("click", ".teste", function (e) {
do_click(e, singleClick, $(this))
})
.on("dblclick", ".teste", function (e) {
do_dblclick(e, doubleClick, $(this))
})
let singleClick = function (element) { // your function when is single click
console.log(element)
}
let doubleClick = function (element) { // your function when is double click
console.log(element)
}
Related
I want it so that when I click on a box in a-scene it runs a function
document.querySelector('p').addEventListener('click', function (evt) {
console.log('This element was clicked!');
});
I tried this but it is not working
Also, you can see https://aframe.io/docs/0.8.0/introduction/interactions-and-controllers.html
Try this JS code, should fix your problem:
const paragraphs = document.getElementsByTagName('p');
for (paragraph of paragraphs) {
paragraph.addEventListener('click', function(e) {
console.log("Hello it worked!")
})
}
I am having an issue with CKeditor click event and double-click events.
Currently, I am binding click event and double click event to the CKEditor dom.
editor.on('doubleclick', function (evt) {
console.log("doubleclicked");
//Some ajax calls
}, null, null, 999 );
editor.on('click', function (evt) {
console.log("clicked");
//Some ajax calls
}, null, null);
An issue with above code is, it fires click event first as well when I double-click the element. Both codes execute when I double click on the element.
Any solution for CKEditor for above case?
My question is related to CKeditor plugin. So I have to bind proper (built-in) events for click and double click.
Try this. It will work. For CKeditor you can replace editor.on('dblclick', function (evt) { line with this line editor.on('doubleclick', function (evt) {
Check this link.
function singleClick(e) {
console.log('single click');
}
function doubleClick(e) {
console.log('double click');
}
editor.on('dblclick', function (evt) {
$(this).data('double', 2);
doubleClick.call(this, evt);
//Some ajax calls
}, null, null, 999 );
editor.on('click', function (evt) {
var that = this;
setTimeout(function() {
var dblclick = parseInt($(that).data('double'), 10);
if (dblclick > 0) {
$(that).data('double', dblclick-1);
} else {
singleClick.call(that, evt);
}
}, 300);
//Some ajax calls
}, null, null);
I am using jquery to find each target element in iframe on click event. But the click event triggers mutiple times on each click. This is the code that i used. I am using this function to style each target element on click. How can i solve this issue.
var getElement = function () {
$('[data-edit="froala"]').on('froalaEditor.initialized', function (e, editor) {
var $div_tag = $('[data-edit="froala"]').find('iframe').contents().find('body');
$div_tag.on('click', function(e) {
var element_name = e.target.nodeName.toLowerCase();
var $target_class = $('[data-target="'+element_name+'"]');
trigger_object(e);
});
});
}
var trigger_object = function (e) {
$('body').on('change', '[data-style="hr-style"]', function (event) {
$(e.target).css($(this).data('css'),this.value);
});
$('body').on('change', '[data-style="div-style"]', function (event) {
$(e.target).css($(this).data('css'),this.value);
});
}
unbind your existing change event before binding it to prevent event from working multiple times
add .off('change') to unbind all exiting change event
before .on('change') to bind the change event
$('[data-style="hr-style"]').off('change').on('change', function (event) {
$(e.target).css($(this).data('css'),this.value);
});
$('[data-style="div-style"]').off('change').on('change', function (event) {
$(e.target).css($(this).data('css'),this.value);
});
Then probably foralaEditor.initialized is fired multiple times.
Try with off, but on the div_tag click not on body,
var getElement = function () {
$('[data-edit="froala"]').on('froalaEditor.initialized', function (e, editor) {
var $div_tag = $('[data-edit="froala"]').find('iframe')contents().find('body');
$div_tag.off('click').on('click', function(e) {
var element_name = e.target.nodeName.toLowerCase();
var $target_class = $('[data-target="'+element_name+'"]');
trigger_object(e);
});
});
}
I have a function "single_double_click" and I am invoking the same via $('#packagelisttable tr').single_double_click(fn), which works fine with static data.
However it is not responding when I am deploying the same application to work with dynamic data.
I tried using .on also as mentioned in several posts but then also no success.Please find the same below:
$(#packagelisttable ).on('single_double_click', 'tr', fn)
$(document).on('single_double_click', 'packagelisttable tr', fn)
I need to click on a row of table (#packagelisttable) and need to check whether it was a single or double click.
Please find the code which I am using:
jQuery.fn.single_double_click = function (single_click_callback, double_click_callback, timeout) {
return this.each(function () {
var clicks = 0,
self = this;
jQuery(this).click(function (event) {
clicks++;
if (clicks == 1) {
setTimeout(function () {
if (clicks == 1) {
single_click_callback.call(self, event);
} else {
double_click_callback.call(self, event);
}
clicks = 0;
}, timeout || 300);
}
});
});
}
//$(#packagelisttable ).on('single_double_click', 'tr', function(){
//$(document).on('single_double_click', 'packagelisttable tr', function(){
// $('#packagelisttable tr').single_double_click(function () {
alert("Try double-clicking me!")
},
function () {
alert("Double click detected")
});
The delegated event version of on is used for events, but single_double_click is not an event. It is a function.
It is not possible to connect a jQuery plugin/function to a dynamically loaded elements that way.
You either need to connect any new elements to your plugin after load, or change the plugin to use classes (e.g. class="singleordouble") and use a delegated click event handler, or you can add a selector as an additional parameter and attach to a non-changing ancestor element (as Cerlin Boss demonstrates).
e.g.
jQuery(document).on('click', '.singleordouble', function (event) {
But if you do that, using a plugin becomes pointless.
It is more flexible to generate your own custom click events, using the settimeout trick you already have.
Here is a full example using custom events: http://jsfiddle.net/TrueBlueAussie/wjf829ap/2/
Run this code once anywhere:
// Listen for any clicks on the desired
$(document).on('click', '.singleordouble', function (e) {
var $this = $(this);
var clicks = $this.data("clicks") || 0;
// increment click counter (from data stored against this element)
$(this).data("clicks", ++clicks);
// if we are on the first click, wait for a possible second click
if (clicks == 1) {
setTimeout(function () {
var clicks = $this.data("clicks");
if (clicks == 1) {
$this.trigger("customsingleclick");
} else {
$this.trigger("customdoubleclick");
}
$this.data("clicks", 0);
}, 300);
}
});
It will generate custom events (called customsingleclick and `customdoubleclick in this example, but call them whatever you want).
You can then simply listen for these custom events:
$(document).on('customsingleclick', function(e){
console.log("single click on " + e.target.id);
});
$(document).on('customdoubleclick', function(e){
console.log("double click on " + e.target.id);
});
Or using delegated event handlers: http://jsfiddle.net/TrueBlueAussie/wjf829ap/3/
$(document).on('customsingleclick', '.singleordouble', function(){
console.log("single click on " + this.id);
});
$(document).on('customdoubleclick', '.singleordouble', function(){
console.log("double click on " + this.id);
});
how about this
I have made some small changes to your code. Not sure if this will work for you.
I have added one more parameter which takes a selector. Please comment if you have any doubt.
jQuery.fn.single_double_click = function (selector, single_click_callback, double_click_callback, timeout) {
return this.each(function () {
var clicks = 0,
self = this;
jQuery(this).on('click', selector, function (event) {
clicks++;
if (clicks == 1) {
setTimeout(function () {
if (clicks == 1) {
single_click_callback.call(self, event);
} else {
double_click_callback.call(self, event);
}
clicks = 0;
}, timeout || 300);
}
});
});
}
Usage :
$('#headmnu').single_double_click('li',
function () {
; // not doing anything here
}, function () {
alert('twice')
});
Here li is the child of the first jquery selector($('#headmnu')) which is a ul
This will work with dynamically added elements also.
UPDATE
Just to clarify $('#headmnu') is a parent element of all lis.
I have used event delegation here to achieve this. Please refer the documentation for more info
I checked your code and if you have pasted, then you should also check
$(#packagelisttable ).on('single_double_click', 'tr', fn) // shold be
$('#packagelisttable').on('single_double_click', 'tr', fn)
$(document).on('single_double_click', 'packagelisttable tr', fn) // should be
$(document).on('single_double_click', '#packagelisttable tr', fn)
i have the following function which lets my elements bounce every time i click on them. how can i achive that i can only click once on each element and if i click a second time to get an alert ("already clicked me")?
// Bounce On Click
function bounceOnClick(view) {
// If the view is a normal view (not a scrollview)
if (view instanceof View) {
// Listen to a click event
view.on("click", function (event) {
// Stop sending the click event to underlying views after this
event.stopPropagation()
// "Wind up" the spring
view.scale = 0.7
// And scale back to full size with a spring curve
view.animate({
properties: {
scale: 1.0
},
curve: "spring(1000,15,500)"
})
})
}
}
// Loop through all the exported views
for (var layerGroupName in PSD) {
bounceOnClick(PSD[layerGroupName]);
}
In JavaScript all objects are dynamic, so you can add properties to view:
view.on("click", function (event) {
if (this.clicked) {
alert("already clicked!");
} else {
// your code
this.clicked = true;
}
});
You can use jquery .one()
Jquery .one() :- Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
Try this :
view.one("click", function (event) {
// Your Code
});
Something like this should do it:
function bounceOnClick(view) {
if (view instanceof View) {
// Listen to a click event, and run this handler only once.
view.one("click", function (event) {
event.stopPropagation();
view.scale = 0.7;
view.animate({
properties: {
scale: 1.0
},
curve: "spring(1000,15,500)"
})
// New event handler: notify the user the element was clicked before.
view.on("click", function (event) {
event.stopPropagation();
alert("already clicked me!");
})
})
}
}
This uses jQuery's .one() event handler to run the first function only once, and then assigns a new event handler with the "already clicked me!" alert.