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);
});
});
}
Related
I have a form and on click on an input, I'm adding classes to that input's wrapped div.
To do this, I've made use of blur and executing my function on click. However, on some cases (very rarely) it will work (and add the class). But majority of the time, it doesn't perform the click action (because the console.log("click") doesn't appear).
My thinking is that maybe the browser is conflicting between the blur and click. I have also tried changing click to focus, but still the same results.
Demo:
$(function() {
var input_field = $("form .input-wrapper input");
$("form .input-wrapper").addClass("noData");
function checkInputHasValue() {
$(input_field).on('blur', function(e) {
var value = $(this).val();
if (value) {
$(this).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("hasData");
} else {
$(this).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("noData");
}
});
}
$(input_field).click(function() {
checkInputHasValue();
console.log("click");
});
});
i've done some modification in your code .
function checkInputHasValue(e) {
var value = $(e).val()
if (value) {
$(e).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("hasData");
} else {
$(e).parent().closest(".input-wrapper").removeClass("hasData noData").addClass("noData");
}
}
$(document).on('blur',input_field, function(e) {
checkInputHasValue($(this));
});
$(document).on("click",input_field,function() {
checkInputHasValue($(this));
console.log("click");
});
In order to avoid conflits between events, you would separate the events and your value check. In your code, the blur event may occur multiple times.
The following code seems ok, as far as I can tell ^^
$(function() {
var input_field = $("form .input-wrapper input");
$("form .input-wrapper").addClass("noData");
function checkInputHasValue(el) {
let target = $(el).closest(".input-wrapper");
var value = $(el).val();
$(target).removeClass("hasData noData");
$(target).addClass(value.length == 0 ? "noData" : "hasData");
console.log("hasData ?", $(target).hasClass("hasData"));
}
$(input_field).on("click", function() {
console.log("click");
checkInputHasValue(this);
});
$(input_field).on("blur", function() {
checkInputHasValue(this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-wrapper">
<input>
</div>
</form>
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)
}
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 something like this:
function SetTableBehavior() {
$(".displayData tr").hover(function(e) {
$(this).children().addClass('displayDataMouseOver');
}, function () {
$(this).children().removeClass('displayDataMouseOver');
});
$(".displayData tr td").click(function(e) {
var rowsSel = $(".displayData .displayDataRowSelected");
for (var i = 0; i < rowsSel.length; i++) {
var rowSel = rowsSel[i];
$(rowSel).children().removeClass("displayDataRowSelected");
}
$(this).parent().addClass('displayDataRowSelected');
var p = $(this).parent();
p.children().addClass('displayDataRowSelected');
});
}
When the body of the table is injected neither hover or click work.
If i use
$(".displayData tr td").live('click',function(e) {
the click event works but
$(".displayData tr").live('hover',function(e) {
doesn't work
What is the solution so that hover works.
Thanks.
It seems to work like this:
function SetTableBehavior() {
$(".displayData tr").live('mouseenter', function (e) {
$(this).children().addClass('displayDataMouseOver');
}).live('mouseleave', function(e) {
$(this).children().removeClass('displayDataMouseOver');
});
$(".displayData tr td").live('click',function(e) {
var rowsSel = $(".displayData .displayDataRowSelected");
for (var i = 0; i < rowsSel.length; i++) {
var rowSel = rowsSel[i];
$(rowSel).children().removeClass("displayDataRowSelected");
}
$(this).parent().addClass('displayDataRowSelected');
var p = $(this).parent();
p.children().addClass('displayDataRowSelected');
});
}
$(".hoverme").live("mouseover mouseout", function(event) {
if ( event.type == "mouseover" ) {
// do something on mouseover
} else {
// do something on mouseout
}
});
From here: http://api.jquery.com/live/
There is no event called "hover" so you can't use it with live or bind. It is just a "short-cut" that jQuery implemented for us.
You cannot use hover with live. You'll have to split it up in 2 separate event listeners: one for mouseenter, and another one for mouseleave.
Additionally, in your situation, you don't need live. Use delegate, which is much better for performance:
$(".displayData").delegate('tr', 'mouseeneter',function(e) {
$(this).children().addClass('displayDataMouseOver');
})
.delegate('tr', 'mouseleave',function(e) {
$(this).children().removeClass('displayDataMouseOver');
});
hover(a, b) is a shortcut for mouseenter(a).mouseleave(b) (which themselves, are shortcuts for bind('mouseenter', a).bind('mouseleave', b)), so try:
$(".displayData tr").live('mouseenter', function(e) {
// mouseenter handler
}).live('mouseleave', function (e) {
// mouseleave handler
});
For more info, see the hover() and live() docs.
I'm trying to figure out how I can wrap the click event. Eg this is the code I want.
$("#test").aclick(function() {
alert('hi');
});
The only thing that aclick does is use the e.preventDefault automatically.
Is it something like?
$.fn.aclick = function(e) {
e.preventDefault();
return $.fn.click.apply(this, arguments);
});
Thanks.
When binding a handler, the event object e doesn't exist yet. You need to create a default event handler that calls the supplied one:
$.fn.aclick = function (handler) {
return this.each(function () {
var el = this;
$(el).click(function (e) {
e.preventDefault();
handler.call(el, e);
});
});
};