jQuery 'on' not registering in dynamically generated modal popup - ajax

I was under the impression that jQuery's on event handler was meant to be able to 'listen' for dynamically created elements AND that it was supposed to replace the behavior of live. However, what I have experienced is that using on is not capturing the click event whereas using live is succeeding!
The tricky aspect of my situation is that I am not only dynamically creating content but I'm doing it via an AJAX .get() call, and inserting the resultant HTML into a modal .dialog() jQueryUI popup.
Here is a simplified version of what I was trying to accomplish (wrapped in $(document).ready(...) ):
$.get("getUserDataAjax.php", queryString, function(formToDisplay) {
$("#dialog").dialog({
autoOpen: true,
modal: true,
buttons...
}).html(formToDisplay);
});
$(".classThatExistsInFormToDisplay").on("click", function() {
alert("This doesn't get called");
});
From the documentation for on I found this which which was how I was approaching writing my on event:
$("p").on("click", function(){
alert( $(this).text() );
});
However, for some reason, live will work as I expect -- whereas on is failing me.
This isn't a question for "how can I make it work" because I have found that on will succeed (capture clicks) if I declare it inside the function(formToDisplay) callback.
My question is: what is wrong with on that it isn't finding my dynamically created elements within a modal popup? My jQuery instance is jquery-1.7.2. jQueryUI is 1.8.21.
Here are two jsFiddles that approximate the issue. Click the word "Test" in both instances to see the different behavior. The only difference in code is replacing on for live.
Where the click is captured by live.
Where the click is NOT captured by on (click 'Test - click me' to see nothing happen).
I realize I may just be using on inappropriately or asking it to do something that was not intended but I want to know why it is not working (but if you have something terribly clever, feel free to share). Thanks for your wisdom!
Update / Answer / Solution:
According to user 'undefined', the difference is that on is not delegated all the way from the top of the document object whereas live does/is.
As Claudio mentions, there are portions of the on documentation that reference dynamically created elements and that what you include in the $("") part of the query needs to exist at runtime.
Here is my new solution: Capture click events on my modal dialog, which, although it does not have any content when the event is created at runtime, will be able to find my content and element with special class that gets generated later.
$("#dialog").on("click", ".classThatExistsInFormToDisplay", function() {
... //(success! Event captured)
});
Thanks so much!

live delegates the event from document object, but on doesn't, if you want to delegate the event using on method, you should delegate the event from one of static parents of the element or document object:
$(document).on("click", ".clickHandle", function() {
alert("Content clicked");
});

The problem is that the element to which you attach the event has to exist.
You have to use on like this to capture clicks on p tags created dynamically
$("#existingContainerId").on("click", "p", function(){
alert( $(this).text() );
});
if you have no relevant existing container to use, you could use $("body") or $(document)
If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next
Take a look to section Direct and delegated events here for more details

Related

CKEDITOR how to Identify scroll event

Does anyone know how to catch the 'scroll' event in CKEDITOR? there is easy to identify change and other events, but I am unable to cathc Scroll event..
CKEDITOR.instances[i].on('change', function() {alert('text changed!');});
but when want to use same for scroll it does not working
CKEDITOR.instances[i].on('scroll', function() {alert('I am scrolling!');});
does anyone know some workaround?
Thx a lot
M
First thing you need to know is that CKEditor's instance (which you get from CKEDITOR.instances object) is not a DOM element. It indeed fires some events like change, focus, blur, or save, but they are just short cuts or facades to more complex things.
Therefore, if you want to add a DOM event listener, then you need to retrieve the "editable" element (an element in which editing happens). It can be accessed by the editor.editable() method. However, the tricky thing about editable element is that it's not always available, it's not ready right after starting editor initialization and that editor may replace this element with a new one (usually after switching between modes). Therefore, editor fires a contentDom to notify that the new editable is available and the editable has an attachListener method which, unlike the on cleans the listener when editable is destroyed.
The way to use all those methods is explained in the documentation and there are code samples, but just to save you one click:
editor.on( 'contentDom', function() {
var editable = editor.editable();
editable.attachListener( editable.getDocument(), 'scroll', function() {
console.log( 'Editable has been scrolled' );
});
});
Update: I forgot that for 'scroll' event you have to listen on document. I updated the code above.

how does jquery's promise method really work?

I don't really understand what delegate and promise are.
According to the docs -
delegate would bind a selector and event to some sort of wrapping container that can be used again at a later time for current and future items.
promise() would remap things back to when it was first bounded if everything newly loaded matches. Maybe I don't really understand this promise method.
What if the wrapper is still there, but the contents in the wrapper container have changed, and/or reloaded via Ajax? Why is it that the events are not triggering or working as it would the first time it is bound?
And yes, I have been to the docs page, I just don't understand their explanations completely.
I'm a bit confused by this question. I think this is because you are confused by promise and delegate. They are in fact completely unrelated features of jQuery. I'll explain each separately:
delegate
delegate is a feature of jQuery that was introduced in jQuery 1.4.2. (It is a nicer approach to the live feature that was added in jQuery 1.3). It solves a particular problem that comes with modifying the DOM, and particularly with AJAX calls.
When you bind an event handler, you bind it to a selection. So you might do $('.special').click(fn) to bind an event handler to all the members of the special class. You bind to those elements, so if you then remove the class from one of those elements, the event will still be triggered. Inversely, if you add the class to an element (or add a new element into the DOM), it won't have the event bound.
There is a feature of Javascript that mitigates this called "event bubbling". When an event is triggered, first the browser notifies the element where the event originated. Then it goes up the DOM tree, and notifies each ancestor element. This means that you can bind an event handler on an element high up the DOM tree, and events triggered on any child elements (even those that don't exist when the handler was bound).
delegate is jQuery's implementation of this. First, you select a parent element. Then you specify a selector – the handler will only be run if the originating element matches this selector. Then you specify an event type, such as click, submit, keydown, just as with bind. Then finally you specify the event handler.
$('#containingElement').delegate('a.special', 'click', function() {
alert('This will happen on all links with the special class');
});
promise
promise is another relatively recent addition to the jQuery featureset. It is part of the Deferred concept that was introduced in jQuery 1.5. (I think the similarity in sound between "deferred" and "delegate" is probably the source of confusion.) This is a way of abstracting away the complications of asynchronous code. The best example of this is with AJAX calls, as the object returned by $.ajax is a Deferred object. For instance:
$.ajax({
url: 'somepage.cgi',
data: {foo: 'bar'}
}).done(function() {
// this will be run when the AJAX request succeeds
}).fail(function() {
// this will be run when the AJAX request fails
}).always(function() {
// this will be run when the AJAX request is complete, whether it fails or succeeds
}).done(function() {
// this will also be run when the AJAX request succeeds
});
So it is in many ways the same as binding success handlers in the $.ajax call, except that you can bind more than one handler, and you can bind them after the initial call.
Another time when it would be useful to deal asynchronously is with animations. You can provide callbacks to functions, but it would be nicer to do this with similar syntax to the AJAX example I've provided above.
In jQuery 1.6, this functionality was made possible, and promise is part of this implementation. You call promise on a jQuery selection, and you'll get an object that you can bind event handlers to, when all the animations in the object have completed.
For instance:
$('div.special').fadeIn(5000).promise().then(function() {
// run when the animation succeeds
}).then(function() {
// also run when the animation succeeds
});
Again, this is similar in effect to traditional methods, but it adds flexibility. You can bind the handlers later, and you can bind more than one.
Summary
Basically, there is no significant relationship between delegate and promise, but they're both useful features in modern jQuery.

Do action after render() method is completed

I need to do some action when render() method finished its work and appended all HTML elements to DOM.
How to subscribe to onRenderEnds event (there is no such event)?
Can I write my own event outside of slickgrid code and attach it to render() method?
There are some events "onScroll", "onViewportChanged" but they happened before render() finished (in some cases).
Update:
I write formatter for column:
formatter: function(row, cell, value, columnDef, dataContext){
return "<div class='operationList' data-my='" + myData + "'></div>";
}
When grid rendered (applying my formatter) i need to go through all ".operationList" divs and convert them to other constructions (based on data-my attribute). I need to replace ".operationList" divs with a complex structure with event handlers.
To answer on my own comment I've come up with the following hack. It may not be pretty but it seems to work.
Add the following line to the render() method just below renderRows(rendered);
function render() {
...
renderRows(rendered);
trigger(self.onRenderCompleted, {}); // fire when rendering is done
...
}
Add a new event handler to the public API:
"onRenderCompleted": new Slick.Event(),
Bind to the new event in your code:
grid.onRenderCompleted.subscribe(function() {
console.log('onRenderCompleted');
});
The basic answer is DON'T !
What you are proposing is a very bad design and goes against the core principles and architecture of SlickGrid.
You will end up doing a lot of redundant work and negating most of the performance advantages of SlickGrid. The grid will create and remove row DOM nodes on the fly as you scroll and do it either synchronously or asynchronously depending on which one suits best at the time. If you must have rich interactive content in the cells, use custom cell renderers and delegate all event handling to the grid level using its provided events such as onClick. If the content of the cell absolutely cannot be created using renderer, use async post-rendering - http://mleibman.github.com/SlickGrid/examples/example10-async-post-render.html. Even so, the grid content should not have any event listeners registered directly to the DOM nodes.
To address #magiconair's comment, you really shouldn't render a whole SELECT with all its options and event handlers until a cell switches into edit mode.

Google Chrome Extension - How can I include a content script more than once?

I've been working on Chrome Extension for a website for the past couple of days. It's coming along really nicely but I've encountered a problem that you might be able to help with.
Here's an outline of what the extension does (this functionality is complete):
A user can enter their username and password into the extensions popup - and verify their user account for the particular website
When a user browses http://twitter.com a content script is dynamically included that manipulates the DOM to include an extra button next to each tweet displayed.
When a user clicks this button they are presented with a dialog box
I've made a lot of progress but here is my problem:
When a user visits Twitter the content script is activated and all tweets on the page get my new button - but if the user then clicks 'More...' and dynamically loads the next 20 tweets... these new additions to the page DOM do not get affected by the content script (because it is already loaded).
I could add an event listener to the 'More...' button so it then triggers the original content script again (and adds the new button) but i would have to predict the length of twitter's ajax request response.
I can't tap into their Ajax request that pulls in more tweets and call my addCurateButton() function once the request is complete.
What do you think is the best solution? (if there is one)
What you want to do is to re-execute your content-script every time the DOM is changed. Luckily there is an event for that. Have a look at the mutation event called DOMNodeInserted.
Rewrite your content script so that it attaches an event listener to the body of the DOM for the DOMNodeInserted event. See the example below:
var isActive = false;
/* Your function that injects your buttons */
var inject = function() {
if (isActive) {
console.log('INFO: Injection already active');
return;
}
try {
isActive = true;
//inject your buttons here
//for the sake of the example I just put an alert here.
alert("Hello. The DOM just changed.");
} catch(e) {
console.error("ERROR: " + e.toString());
} finally {
isActive = false;
}
};
document.body.addEventListener("DOMNodeInserted", inject, false);
The last line will add the event listener. When a page loads the event is triggered quite often so you should define a boolean (e.g. var isActive), that you initialize to false. Whenever the inject function is run check whether isActive == true and then abort the injection to not execute it too often at the same time.
Interacting with Ajax is probably the hardest thing to coax a content script to do, but I think you’re on the right track. There are a couple different approaches I’ve taken to solving this problem. In your case, though, I think a combination of the two approaches (which I’ll explain last) would be best.
Attach event listeners to the DOM to detect relevant changes. This solution is what you’ve suggested and introduces the race condition.
Continuously inspect the DOM for changes from inside a loop (preferably one executed with setInterval). This solution would be effective, but relatively inefficient.
The best-of-both-worlds approach would be to initiate the inspection loop only after the more button is pressed. This solution would both avoid the timing issue and be efficient.
You can attach an event-handler on the button, or link that is used for fetching more results. Then attach a function to it such that whenever the button is clicked, your extension removes all the buttons from DOM and starts over inserting them, or check weather your button exists in that particular class of DOM element or not and attach a button if it doesn't.

jQuery: Targeting elements added via *non-jQuery* AJAX before any Javascript events fire? Beyond the scope of live()?

Working on a Wicket application that adds markup to the DOM after onLoad via Wicket's built-in AJAX for an auto-complete widget. We have an IE6 glitch that means I need to reposition the markup coming in, and I am trying to avoid tampering with the Wicket javascript... blah blah blah... here's what I'm trying to do:
New markup arrives in the DOM (I
don't have access to a callback)
Somehow I know this, so I fire my
code.
I tried this, hoping the new tags would trigger onLoad events:
$("selectorForNewMarkup").live("onLoad", function(){ //using jQuery 1.4.1
//my code
});
...but have become educated that onLoad only fires on the initial page load. Is there another event fired when elements are added to the DOM? Or another way to sense changes to the DOM?
Everything I've bumped into on similar issues with new markup additions, they have access to the callback function on .load() or similar, or they have a real javascript event to work with and live() works perfectly.
Is this a pipe dream?
.live() doesn't work like this, it's a common misconception. .live() creates an event handler at the DOM root and waits for events to bubble up to it. If the selector matches the event target, .live() will fire the bound event.
It doesn't look for new objects and bind events to them in any way, rather it just listens for a bubble, and doesn't care when that object was added to the DOM.
You need to fire whatever code is needed to run manually when your load operation completes.
What will this is the livequery plug-in, look specifically at the livequery( matchedFn ) call.
You can do something like this:
$('#myID').livequery(function() { $(this).offset()...stuff });
i guess this is what you are looking for http://ananthakumaran.github.com/2010/02/19/wicket-post-ajax-handling.html

Resources