Bind ready event on javascript dom element creation - javascript

i would like to know if we can bind a loaded or ready event on an item created by a script when the dom is loaded. I heard from live() but it's not something clickable, it's just an item which has to load.
Thanks for your help!

I guess your best shot is the load event there.
$('element').load(function(){
alert('loaded');
});
native
var elem = document.getElementById('element_id');
elem.onload = function(){
alert('loaded');
};
Another example for dynamic creation:
$('<img/>', {
src: '/images/myimage.png',
load: function(){
alert('image loaded');
}
}).appendTo(document.body);

If you want to be able to separate the pieces of code for creating the item and the load event handling you could try having your dynamically created element trigger a custom event on the window:
var myElement = $('<img/>', {
src: '/images/myimage.png'
}).appendTo(document.body);
$(window).trigger( {type: "myElementInit", myObject : myElement} );
With a pointer back to itself in the extra parameters, you could then have a separate handler set-up within a jQuery(document).ready to look for the "myElementInit" window event and grab the reference to the element out of the extra parameters:
jQuery.('window').bind( "myElementInit", function(event){
var theElement = event.myObject;
...
} );

You can use the delegated form of the .on() event, as documented here:
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers. This
element could be the container element of a view in a
Model-View-Controller design, for example, or document if the event
handler wants to monitor all bubbling events in the document. The
document element is available in the head of the document before
loading any other HTML, so it is safe to attach events there without
waiting for the document to be ready.

Related

jQuery the new appended data can not be captured by .on()

I am trying to get the value of an input box that been .append() to the HTML recently. The Input box does not exist normally. it get .append() on button click by a function.
The Value of the input should be captured and sent via jQuery Ajax to backend(php).
The Function which append the Input field:
function toggleOrder(){
$(".orderContainer").append(`
<div class="orderFilterBox">
<input id="orderFilterInput" type="text" placeHolder="Enter IMEI">
</div>
`);
}
The Function where the input value captured and sent to backend
$(document).ready(function(){
$("#orderFilterInput").on("change paste",function(){
//DO THE MAGIC
//...
});
});
I belive that the problem being there that the code on the pageload where the input not exist. im not sure how to avoid that.
Also if you would suggsest a better question title to help other people, then please go for it
if you use .on you need focus on static element which exist in page load. orderFilterInput.on is bad if orderFilterInput does not exist.
You can try
$(document).on("ready", function(){
$("body").on("change paste","#orderFilterInput", function(){
//DO THE MAGIC
//...
});
});
or you can make your append button by jquery with event in your append function.
const btn = $('<input id="orderFilterInput" type="text" placeHolder="Enter IMEI">')
.on('copy paste', function() { .. });
$container.append(btn);
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on(). To ensure
the elements are present and can be selected, place scripts after the
elements in the HTML markup or perform event binding inside a document
ready handler. Alternatively, use delegated event handlers to attach
event handlers.
Delegated event handlers have the advantage that they can process
events from descendant elements that are added to the document at a
later time. By picking an element that is guaranteed to be present at
the time the delegated event handler is attached, you can use
delegated event handlers to avoid the need to frequently attach and
remove event handlers. This element could be the container element of
a view in a Model-View-Controller design, for example, or document if
the event handler wants to monitor all bubbling events in the
document. The document element is available in the head of the
document before loading any other HTML, so it is safe to attach events
there without waiting for the document to be ready.
Here is the api reference:
https://api.jquery.com/on/
, So as suggested by #daremachine you need to use the delegated event handler
as:
$(document).on("change paste","#orderFilterInput", function(){
//DO THE MAGIC
//...
});

.on() event handler inside ajaxComplete()?

I have this:
$('.task').on('click', function()
{
task_id = $(this).data('id');
console.log('Task id: ' + task_id);
});
But this doesn't work as it should when the content is reloaded via ajax. task_id value stays the same even after clicking different elements after the ajax reload. Apparently I have to bind it to the body first.
This is how it is in my code right now though (it works as expected):
$(document).ajaxComplete(function(event, xhr, settings) {
$('.task').on('click', function()
{
task_id = $(this).data('id');
console.log('Task id: ' + task_id);
});
});
But I've been told this duplicates/doubles the trigger for the .on('click') event? Is this true? How do I know then when to bind to the direct selector or bind to the document.body instead?
Which would be more efficient? Binding to body or putting the event delegation inside ajaxComplete()?
I'm a little confused too since I have other event handlers inside the same .js file but outside ajaxComplete() that seem to work just fine even after an ajax reload?
You should use .on() method with Event Delegation approach, when generating elements dynamically(content is updated via $.ajax())/manipulating selectors. then you won't need to attach event handler in ajaxComplete()
General Syntax
$(document).on('event','selector',callback_function)
Example
$(document).on('click', '.task', function(){
//Rest of your code
});
In place of document you should use closest static container.
The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

$( document ).ready() in partial view only runs first time it is added to the DOM via AJAX

After using AJAX to load a partial view in to a dialog on the page, this code, located in the partial itself NOT in the main page, runs and I get tabs as expected:
// Run this on page load
$(function () {
debugger;
$("#ProjectTabset").tabs();
});
This being the case, if the div containing the partial was removed from the DOM (using jQuery remove) then added again and the partial loaded in to it once more, it should run again, but it doesn't.
Why would it run the first time, but not any subsequent time? Could the problem be that the div in to which the partial is being inserted is not really removed somehow? (Though I am testing it is not present before creating, and it seems it is no longer part of the DOM.)
Please let me know if I can be more clear or provide any more detail :)
Since you have removed the element from DOM and added back dynamically you may need to use the delegated events via on() if you want events to be handled on dynamically added elements. Try the below and see if it helps.
$( document ).on( 'ready', function (e) {
$("#ProjectTabset").tabs();
})
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.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers.
May be the links here will help you resolve the problem.
You should use .delegate():
// Run this on page load or ajax load complete
$('body').delegate('#ProjectTabset', 'ready', function() {
$("#ProjectTabset").tabs();
});
UPDATE:
$(document).delegate('#ProjectTabset', 'click', function() {
$('#ProjectTabset').tabs();
}
$.ajax(function(){
...
success: function(){
$('#ProjectTabset').click();
}
})

Attach click handler to dynamically generated anchor tag

I dynamically generate some markup and inject it into the DOM like this:
content+='<td><a class="reportLink" onclick="showReport();return false;" href="'+layerResults.features[i].attributes['Information_External']+'">Info</a></td>';
I know it would be better to use jQuery to attach the click handler instead of using an inline handler.
The problems are, even using an inline handler and a function like this:
function showReport() {
console.log('stopped');
}
Still doesn't prevent the link from navigating away from my page.
The second problem is, when I try using
jQuery('.reportLink'.on('click', function(e) {
e.preventDefault();
console.log('clicked');
});
The event never gets attached. I'm using jQuery 1.7.2.
This is driving me a bit insane as it's a simple task I've done about a zillion times in jQuery <= 1.5.
Delegate the event handler to a parent element that exists at the time the dom is loaded. You can replace body with that parent.
jQuery('body').on('click','.reportLink', function(e){
e.preventDefault();
console.log('clicked');
});
from jquery docs .on()
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.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:
to prevent it from navigating away, enter this right after "console.log('stopped');
return false;
for the second one, i usually use this syntax, maybe it'll help:
jQuery(".reportLink").click(function() {
//do something
});

Does attaching event handler with a class selector affects dynamically added elements of that class?

I am using jQuery to attach a function to my click event for an entire class. For example:
$(".clickDiv").click(function(){
$(this).hide();
});
On my client-side javascript, I create more .clickDiv instances dynamically.
Do I need to call the $(".clickDiv).click(function...) again, or will the new instances automatically have that function bound to the click event?
Yes you do, unless you use a delegate event
like this:
$('#container').on('click', '.clickDiv', function() {
$(this).hide();
});
on docs:
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.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Just because too much people here suggested you should use live, live is deprecated since version 1.7 by on and was replaced in version 1.4.3 by delegate
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
I am attaching an event like :
$('body').on('click', 'button[data-tracking], a[data-tracking]',
function(event) { console.log($(event.target));
});
and want to get to the target of element which is set up as :
<pre> <[]a data-tracking="hello" href="hello">
\<\span\>test now\<\/span\>
\<\/a\>
</pre>
it does work perfectly, but event.target gives me "span" element but what i want is "a" element so that I could get to value of data-tracking attribute.
This will bind the event to all new instances
$('.clickDiv').live('click', function() {
$(this).hide();
});
http://api.jquery.com/live/

Categories

Resources