Yeldho Paul Yeldho Paul - 1 month ago 14
Javascript Question

jquery click event working multiple times

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);
});
}

Answer

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);
});