Merging events from one selector to another - javascript

I would like to know if it's possible to store the events from a jQuery selector and apply it to another selector?
Something similar to $('selector').clone(true) but actually clones the events only and not the element.
$('.class1').on('click.click1', function(e) {
alert('click 1')
});
$('.class2').on('click.click2', function(e) {
alert('click 2')
});
// pseudo
$('.class2') cloneEvents from $('.class1');

Quick and dirty jQuery plugin for this purpose
This reads the event handlers bound to $source via jQuery using the internal method _data, iterates over them and binds them to $target. Derived from this snippet.
;(function($, doc, win) {
"use strict";
$.fn.cloneEventsFrom = function($source) {
var $this = $(this),
source = $source.get(0);
$.each($._data(source, 'events'), function() {
$.each(this, function() {
$this.bind(this.type, this.handler);
});
});
};
})(jQuery, document, window);
Usage Demo here: http://jsfiddle.net/marionebl/4Jv37/1/
var $target = $('.target'),
$source = $('.source')
$target.cloneEventsFrom($source);

Related

jQuery this context to point to the element in context

I have a situation using BS3 modal events and my app functionality is wrapped in object with exposed methods (reveal module pattern). I have event received from BS and I what my $this to point to the Event object instead of the App object.
I tried jquery this context with the jQuery proxy, which seems to be the best thing, but for some reason the things didn't worked for me
var globalAppDef = (function() {
function modalFilters() {
$('#filtersMore')
.on('show.bs.modal', (event) => {
const sourceElement = $(event.relatedTarget);
$(sourceElement.data().filters).removeClass('hidden');
})
/*
* Transfer the proper #this of the event outside the {globalAppDef} Object
*/
.on('hidden.bs.modal', $.proxy((event) => {
$(this).find(".form-list-items-1").addClass('hidden');
$(this).find(".form-list-items-1").addClass('hidden');
}, this));
}
return modalFilters: modalFilters
}
});
var globalApp = new globalAppDef();
globalApp.initialize();
$(document).ready(function () {globalApp.modalFilters()});
What I what to achieve is on the second hidden.bs.modal $this to point to my Modal, which is $('#filtersMore') element.
actually it it was the Arrow function the reason for that this stayed in the Object context.
That way worked:
.on('hidden.bs.modal', $.proxy(function (event) {
$(this).find(".form-list-items-1, .form-list-items-2").addClass('hidden');
}, $('#filtersMore')));

JQuery Plugin - triggering internal functions by callback

Skip to bottom for question
JQuery plugin:
$.fn.myPlugin = function( options ) {
var options = $.extend({
myOption: true,
edit: function() {},
done: function() {}
}, options);
options.edit.call(this);
options.done.call(this);
//plugin guts removed to prevent over complication
return {
edit: function(obj) {
$(obj).closest('#myParent').find('#myInput').autosizeInput(); //plugin to autosize an input
},
done: function(obj) {
$(this).closest('tr').find('td').not('.not').each(function(i) {
//do some things
});
}
}
});
Bear in mind this is a cut down version of my plugin.
Called from page:
$(document).ready(function() {
var myPlugin = $('.editable').myPlugin({
edit: $(this).on('click', '.edit-td', function(e) {
e.preventDefault();
//do some page specific stuff
myPlugin.edit( $(this) ); //call the edit returned function
}),
done: $(this).on('click', '.done-td', function(e) {
e.preventDefault();
//do some page specific stuff
myPlugin.done( $(this) ); //call the done returned function
});
});
});
This works great for the most part, however, what i really want is have functions called from inside my plugin every time a specific callback is triggered - without the need to call from outside the plugin.
I have tried including delegated events in my plugin:
$(this).on('click', '.edit-td', function(e) {
e.preventDefault();
$(this).closest('#myParent').find('#myInput').autosizeInput();
});
$(this).on('click', '.done-td', function(e) {
e.preventDefault();
$(this).closest('tr').find('td').not('.not').each(function(i) {
//do some things
});
});
But when the .edit-td is triggered it propagates and triggers the .done-td event, if i put e.stopPropagation() in the edit-td function (because it has been delegated) edit-td stops firing completely.
And non-delegated method:
$(this).find('.done-td').click(function(e, this) {});
But I can't parse the returned object (this) to the internal function before the internal function has completed. (just comes up undefined or missing formal parameter).
*Skip to here
To avoid the question becoming to localised -
I need to have functions called from inside my
plugin every time a specific callback is triggered.
Without calling it using closures
Something like:
if( $.fn.myPlugin.callback().is('edit') ) {
//fire function
}
I needed to return a function(s) like so:
return {
enable: function(arg) {
//do something
},
disable: function(arg) {
//do something
}
}
That way I can call it from inside my plugin by referencing itself like this:
this.myPlugin().disable();

jQuery "on create" event for dynamically-created elements

I need to be able to dynamically create <select> element and turn it into jQuery .combobox(). This should be element creation event, as opposed to some "click" event in which case I could just use jQuery .on().
So does something like this exist?
$(document).on("create", "select", function() {
$(this).combobox();
}
I'm reluctant to use livequery, because it's very outdated.
UPDATE The mentioned select/combobox is loaded via ajax into a jQuery colorbox (modal window), thus the problem - I can only initiate combobox using colorbox onComplete, however on change of one combobox another select/combobox must be dynamically created, therefor I need a more generic way to detect creation of an element (selectin this case).
UPDATE2 To try and explain the problem further - I have select/combobox elements created recursively, there is also a lot of initiating code inside .combobox(), therefore if I used a classic approach, like in #bipen's answer, my code would inflate to insane levels. Hope this explains the problem better.
UPDATE3 Thanks everyone, I now understand that since deprecation of DOMNodeInserted there is a void left in DOM mutation and there is no solution to this problem. I'll just have to rethink my application.
You can on the DOMNodeInserted event to get an event for when it's added to the document by your code.
$('body').on('DOMNodeInserted', 'select', function () {
//$(this).combobox();
});
$('<select>').appendTo('body');
$('<select>').appendTo('body');
Fiddled here: http://jsfiddle.net/Codesleuth/qLAB2/3/
EDIT: after reading around I just need to double check DOMNodeInserted won't cause problems across browsers. This question from 2010 suggests IE doesn't support the event, so test it if you can.
See here: [link] Warning! the DOMNodeInserted event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.
As mentioned in several other answers, mutation events have been deprecated, so you should use MutationObserver instead. Since nobody has given any details on that yet, here it goes...
Basic JavaScript API
The API for MutationObserver is fairly simple. It's not quite as simple as the mutation events, but it's still okay.
function callback(records) {
records.forEach(function (record) {
var list = record.addedNodes;
var i = list.length - 1;
for ( ; i > -1; i-- ) {
if (list[i].nodeName === 'SELECT') {
// Insert code here...
console.log(list[i]);
}
}
});
}
var observer = new MutationObserver(callback);
var targetNode = document.body;
observer.observe(targetNode, { childList: true, subtree: true });
<script>
// For testing
setTimeout(function() {
var $el = document.createElement('select');
document.body.appendChild($el);
}, 500);
</script>
Let's break that down.
var observer = new MutationObserver(callback);
This creates the observer. The observer isn't watching anything yet; this is just where the event listener gets attached.
observer.observe(targetNode, { childList: true, subtree: true });
This makes the observer start up. The first argument is the node that the observer will watch for changes on. The second argument is the options for what to watch for.
childList means I want to watch for child elements being added or removed.
subtree is a modifier that extends childList to watch for changes anywhere in this element's subtree (otherwise, it would just look at changes directly within targetNode).
The other two main options besides childList are attributes and characterData, which mean about what they sound like. You must use one of those three.
function callback(records) {
records.forEach(function (record) {
Things get a little tricky inside the callback. The callback receives an array of MutationRecords. Each MutationRecord can describe several changes of one type (childList, attributes, or characterData). Since I only told the observer to watch for childList, I won't bother checking the type.
var list = record.addedNodes;
Right here I grab a NodeList of all the child nodes that were added. This will be empty for all the records where nodes aren't added (and there may be many such records).
From there on, I loop through the added nodes and find any that are <select> elements.
Nothing really complex here.
jQuery
...but you asked for jQuery. Fine.
(function($) {
var observers = [];
$.event.special.domNodeInserted = {
setup: function setup(data, namespaces) {
var observer = new MutationObserver(checkObservers);
observers.push([this, observer, []]);
},
teardown: function teardown(namespaces) {
var obs = getObserverData(this);
obs[1].disconnect();
observers = $.grep(observers, function(item) {
return item !== obs;
});
},
remove: function remove(handleObj) {
var obs = getObserverData(this);
obs[2] = obs[2].filter(function(event) {
return event[0] !== handleObj.selector && event[1] !== handleObj.handler;
});
},
add: function add(handleObj) {
var obs = getObserverData(this);
var opts = $.extend({}, {
childList: true,
subtree: true
}, handleObj.data);
obs[1].observe(this, opts);
obs[2].push([handleObj.selector, handleObj.handler]);
}
};
function getObserverData(element) {
var $el = $(element);
return $.grep(observers, function(item) {
return $el.is(item[0]);
})[0];
}
function checkObservers(records, observer) {
var obs = $.grep(observers, function(item) {
return item[1] === observer;
})[0];
var triggers = obs[2];
var changes = [];
records.forEach(function(record) {
if (record.type === 'attributes') {
if (changes.indexOf(record.target) === -1) {
changes.push(record.target);
}
return;
}
$(record.addedNodes).toArray().forEach(function(el) {
if (changes.indexOf(el) === -1) {
changes.push(el);
}
})
});
triggers.forEach(function checkTrigger(item) {
changes.forEach(function(el) {
var $el = $(el);
if ($el.is(item[0])) {
$el.trigger('domNodeInserted');
}
});
});
}
})(jQuery);
This creates a new event called domNodeInserted, using the jQuery special events API. You can use it like so:
$(document).on("domNodeInserted", "select", function () {
$(this).combobox();
});
I would personally suggest looking for a class because some libraries will create select elements for testing purposes.
Naturally, you can also use .off("domNodeInserted", ...) or fine-tune the watching by passing in data like this:
$(document.body).on("domNodeInserted", "select.test", {
attributes: true,
subtree: false
}, function () {
$(this).combobox();
});
This would trigger checking for the appearance of a select.test element whenever attributes changed for elements directly inside the body.
You can see it live below or on jsFiddle.
(function($) {
$(document).on("domNodeInserted", "select", function() {
console.log(this);
//$(this).combobox();
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// For testing
setTimeout(function() {
var $el = document.createElement('select');
document.body.appendChild($el);
}, 500);
</script>
<script>
(function($) {
var observers = [];
$.event.special.domNodeInserted = {
setup: function setup(data, namespaces) {
var observer = new MutationObserver(checkObservers);
observers.push([this, observer, []]);
},
teardown: function teardown(namespaces) {
var obs = getObserverData(this);
obs[1].disconnect();
observers = $.grep(observers, function(item) {
return item !== obs;
});
},
remove: function remove(handleObj) {
var obs = getObserverData(this);
obs[2] = obs[2].filter(function(event) {
return event[0] !== handleObj.selector && event[1] !== handleObj.handler;
});
},
add: function add(handleObj) {
var obs = getObserverData(this);
var opts = $.extend({}, {
childList: true,
subtree: true
}, handleObj.data);
obs[1].observe(this, opts);
obs[2].push([handleObj.selector, handleObj.handler]);
}
};
function getObserverData(element) {
var $el = $(element);
return $.grep(observers, function(item) {
return $el.is(item[0]);
})[0];
}
function checkObservers(records, observer) {
var obs = $.grep(observers, function(item) {
return item[1] === observer;
})[0];
var triggers = obs[2];
var changes = [];
records.forEach(function(record) {
if (record.type === 'attributes') {
if (changes.indexOf(record.target) === -1) {
changes.push(record.target);
}
return;
}
$(record.addedNodes).toArray().forEach(function(el) {
if (changes.indexOf(el) === -1) {
changes.push(el);
}
})
});
triggers.forEach(function checkTrigger(item) {
changes.forEach(function(el) {
var $el = $(el);
if ($el.is(item[0])) {
$el.trigger('domNodeInserted');
}
});
});
}
})(jQuery);
</script>
Note
This jQuery code is a fairly basic implementation. It does not trigger in cases where modifications elsewhere make your selector valid.
For example, suppose your selector is .test select and the document already has a <select>. Adding the class test to <body> will make the selector valid, but because I only check record.target and record.addedNodes, the event would not fire. The change has to happen to the element you wish to select itself.
This could be avoided by querying for the selector whenever mutations happen. I chose not to do that to avoid causing duplicate events for elements that had already been handled. Properly dealing with adjacent or general sibling combinators would make things even trickier.
For a more comprehensive solution, see https://github.com/pie6k/jquery.initialize, as mentioned in Damien Ó Ceallaigh's answer. However, the author of that library has announced that the library is old and suggests that you shouldn't use jQuery for this.
You can use DOMNodeInserted mutation event (no need delegation):
$('body').on('DOMNodeInserted', function(e) {
var target = e.target; //inserted element;
});
EDIT: Mutation events are deprecated, use mutation observer instead
Just came up with this solution that seems to solve all my ajax problems.
For on ready events I now use this:
function loaded(selector, callback){
//trigger after page load.
$(function () {
callback($(selector));
});
//trigger after page update eg ajax event or jquery insert.
$(document).on('DOMNodeInserted', selector, function () {
callback($(this));
});
}
loaded('.foo', function(el){
//some action
el.css('background', 'black');
});
And for normal trigger events I now use this:
$(document).on('click', '.foo', function () {
//some action
$(this).css('background', 'pink');
});
There is a plugin, adampietrasiak/jquery.initialize, which is based on MutationObserver that achieves this simply.
$.initialize(".some-element", function() {
$(this).css("color", "blue");
});
This could be done with DOM4 MutationObservers but will only work in Firefox 14+/Chrome 18+ (for now).
However there is an "epic hack" (author's words not mine!) that works in all browsers that support CSS3 animations which are: IE10, Firefox 5+, Chrome 3+, Opera 12, Android 2.0+, Safari 4+. See the demo from the blog. The hack is to use a CSS3 animation event with a given name that is observed and acted upon in JavaScript.
One way, which seems reliable (though tested only in Firefox and Chrome) is to use JavaScript to listen for the animationend (or its camelCased, and prefixed, sibling animationEnd) event, and apply a short-lived (in the demo 0.01 second) animation to the element-type you plan to add. This, of course, is not an onCreate event, but approximates (in compliant browsers) an onInsertion type of event; the following is a proof-of-concept:
$(document).on('webkitAnimationEnd animationend MSAnimationEnd oanimationend', function(e){
var eTarget = e.target;
console.log(eTarget.tagName.toLowerCase() + ' added to ' + eTarget.parentNode.tagName.toLowerCase());
$(eTarget).draggable(); // or whatever other method you'd prefer
});
With the following HTML:
<div class="wrapper">
<button class="add">add a div element</button>
</div>
And (abbreviated, prefixed-versions-removed though present in the Fiddle, below) CSS:
/* vendor-prefixed alternatives removed for brevity */
#keyframes added {
0% {
color: #fff;
}
}
div {
color: #000;
/* vendor-prefixed properties removed for brevity */
animation: added 0.01s linear;
animation-iteration-count: 1;
}
JS Fiddle demo.
Obviously the CSS can be adjusted to suit the placement of the relevant elements, as well as the selector used in the jQuery (it should really be as close to the point of insertion as possible).
Documentation of the event-names:
Mozilla | animationend
Microsoft | MSAnimationEnd
Opera | oanimationend
Webkit | webkitAnimationEnd
W3C | animationend
References:
caniuse.com summary of compatibility of CSS Animations.
CSS AnimationEvent Interface (W3C).
JavaScript animationend vendor-support.
For me binding to the body does not work. Binding to the document using jQuery.bind() does.
$(document).bind('DOMNodeInserted',function(e){
var target = e.target;
});
instead of...
$(".class").click( function() {
// do something
});
You can write...
$('body').on('click', '.class', function() {
// do something
});
I Think it's worth mentioning that in some cases, this would work:
$( document ).ajaxComplete(function() {
// Do Stuff
});
create a <select> with id , append it to document.. and call .combobox
var dynamicScript='<select id="selectid"><option value="1">...</option>.....</select>'
$('body').append(dynamicScript); //append this to the place your wanted.
$('#selectid').combobox(); //get the id and add .combobox();
this should do the trick.. you can hide the select if you want and after .combobox show it..or else use find..
$(document).find('select').combobox() //though this is not good performancewise
if you are using angularjs you can write your own directive. I had the same problem whith bootstrapSwitch. I have to call
$("[name='my-checkbox']").bootstrapSwitch();
in javascript but my html input object was not created at that time. So I write an own directive and create the input element with
<input type="checkbox" checkbox-switch>
In the directive I compile the element to get access via javascript an execute the jquery command (like your .combobox() command). Very important is to remove the attribute. Otherwise this directive will call itself and you have build a loop
app.directive("checkboxSwitch", function($compile) {
return {
link: function($scope, element) {
var input = element[0];
input.removeAttribute("checkbox-switch");
var inputCompiled = $compile(input)($scope.$parent);
inputCompiled.bootstrapSwitch();
}
}
});

JQuery event tracking

in some function I remove element like this $('#'+id+' img.load').remove(); , how can i track this event and run custom code?
(function($){
var remove_orig = $.fn.remove;
$.fn.remove = function(){
console.log('Remove called');
remove_orig.apply(this, arguments);
};
})(jQuery);
You can "hook" in to any jQuery function and place your own handling code within (including logging method(s)) which will execute before the native jQuery code is executed.
demo (another version with the selector shown)
Catching the removal is easy using the above overload. Simply alter the hook to fire a trigger before (or after) jQuery gets to it:
(function($){
var remove_orig = $.fn.remove;
$.fn.remove = function(){
this.trigger('removing');
remove_orig.apply(this, arguments);
};
})(jQuery);
$('#foo').bind('removing',function(e){
alert('#foo is being removed');
});
$('#foo').remove();
One way is to "trigger" a custom event (in this example I am using window):
$('#'+id+' img.load').remove();
$(window).trigger("MyElementRemoved", [id]);
Then in another part of your code "handle" the event:
$(window).bind("MyElementRemoved", function(e, elementId) {
alert("element removed: " + elementId);
}

jQuery extension: why does it not work on all matching elements?

I have an extension going like:
$.fn.crazything = function() {
var self = $(this);
// do some crazy stuff
return self;
}
And when I call it like:
$("div.crazydiv").crazything();
It works, but only on the first matching div. If I have more than one div on the page, I need to do:
$("div.crazydiv").each(function(i) { $(this).crazything (); });
Why is this, and how can I rewrite my extension to work on multiple divs?
Most jQuery plugins use this pattern which handles your crazy stuff:
(function($) {
$.fn.crazything = function() {
// allow setup on jQuery objects that conatin multiple elements:
return this.each(function() {
// this function is called once for each element in the jQuery object
var self = $(this);
// do some crazy stuff
});
};
})(jQuery);

Categories