ajax on elements not working for appended content - javascript

I have the following javascript:
<script>
$(document).ready(function() {
$('[class^="commentbubble_"]').click(function () {
var ID = $(this).attr('class').replace('commentbubble_', '');
$('.commentform_'+ID).toggle();
$('#commentsection').masonry( 'reload' );
});
});
</script>
It works for the first page of results...but for newly appended, it won't work. Is there a way to ensure this function works on newly appended content?
Thank you.

You can try with delegation the event to its parent which was available on page load or $(document) itself with .on() handler:
$(document).ready(function() {
$(document).on('click', '[class^="commentbubble_"]', function () {
var ID = $(this).attr('class').replace('commentbubble_', '');
$('.commentform_'+ID).toggle();
$('#commentsection').masonry( 'reload' );
});
});

$().ready only works on the current elements
When you append an element you need bind is click event

Since you are appending data on ajax load after page is loaded, So you need to use .on event handler to bind any event on the element instead of .click event.
Syntax is :
.on( events [, selector ] [, data ], handler(eventObject) )
So your script will be something like this :
<script>
$(document).ready(function() {
$('document).on('click','[class^="commentbubble_"]',function () {
var ID = $(this).attr('class').replace('commentbubble_', '');
$('.commentform_'+ID).toggle();
$('#commentsection').masonry( 'reload' );
});
});
</script>
For more reference, refer http://api.jquery.com/on/

use live
('[class^="commentbubble_"]').live ('click', function () {
Note:
live is deprecated, use on as suggested by #Jai

Related

jQuery alternative for addEventListener for custom attribute

Im working on clicking event script and i need jquery alternative for js addEvetListener for custom attribute.
Here is my js version which does not work and i need jquery alternative:
document.querySelectorAll('[data-slide-number]').forEach(item => {
item.addEventListener('click', event => {
console.log(item.getAttribute("data-slide-number"));
})
})
I need to listen to all elements with data-slide-number attributes so i can use click function on them.
I tried this but its not working:
$('[data-slide-number]').on( "click", function(event) {
alert( $( this ).html() );
console.log( event.target );
} );
And i need to add listener because im trying to execute these functions while clicking on another elements:
$(document).on('click', '#desat', function(event) {
console.log($(this).html());
$('[data-slide-number="9"]').click();
});
$(document).on('click', '#jedenast', function(event) {
console.log($(this).html());
$('[data-slide-number="10"]').click();
});
try
$(document).on('click', '[data-slide-number]', function(){
let _number = $(this).data('slide-number');
slideTo(_number);
});

Trigger AJAX inside an AJAX loaded page [duplicate]

I have a link, myLink, that should insert AJAX-loaded content into a div (appendedContainer) of my HTML page. The problem is that the click event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. The click event is bound on DOM elements that are not loaded with my AJAX function.
What do I have to change, such that the event will be bound?
My HTML:
<a class="LoadFromAjax" href="someurl">Load Ajax</a>
<div class="appendedContainer"></div>
My JavaScript:
$(".LoadFromAjax").on("click", function(event) {
event.preventDefault();
var url = $(this).attr("href"),
appendedContainer = $(".appendedContainer");
$.ajax({
url: url,
type : 'get',
complete : function( qXHR, textStatus ) {
if (textStatus === 'success') {
var data = qXHR.responseText
appendedContainer.hide();
appendedContainer.append(data);
appendedContainer.fadeIn();
}
}
});
});
$(".mylink").on("click", function(event) { alert("new link clicked!");});
The content to be loaded:
<div>some content</div>
<a class="mylink" href="otherurl">Link</a>
Use event delegation for dynamically created elements:
$(document).on("click", '.mylink', function(event) {
alert("new link clicked!");
});
This does actually work, here's an example where I appended an anchor with the class .mylink instead of data - http://jsfiddle.net/EFjzG/
If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!
Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:
$('.parent-element').on('click', '.mylink', function(){
alert ("new link clicked!");
})
Some more reading on the subject:
https://learn.jquery.com/events/event-delegation/
http://jqfundamentals.com/chapter/events
if your question is "how to bind events on ajax loaded content" you can do like this :
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
});
so you don't need to place your configuration to every you ajax code
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
Example -
$( document ).on( events, selector, data, handler );
For those who are still looking for a solution , the best way of doing it is to bind the event on the document itself and not to bind with the event "on ready"
For e.g :
$(function ajaxform_reload() {
$(document).on("submit", ".ajax_forms", function (e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'post',
url: url,
data: $(this).serialize(),
success: function (data) {
// DO WHAT YOU WANT WITH THE RESPONSE
}
});
});
});
If your ajax response are containing html form inputs for instance, than this would be great:
$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) {
if (this.value == 'Yes') {
// do something here
} else if (this.value == 'No') {
// do something else here.
} else {
console.log('The new input field from an ajax response has this value: '+ this.value);
}
});
use jQuery.live() instead . Documentation here
e.g
$("mylink").live("click", function(event) { alert("new link clicked!");});
For ASP.NET try this:
<script type="text/javascript">
Sys.Application.add_load(function() { ... });
</script>
This appears to work on page load and on update panel load
Please find the full discussion here.
Important step for Event binding on Ajax loading content...
01. First of all unbind or off the event on selector
$(".SELECTOR").off();
02. Add event listener on document level
$(document).on("EVENT", '.SELECTOR', function(event) {
console.log("Selector event occurred");
});
Here is my preferred method:
// bind button click to function after button is AJAX loaded
$('#my_button_id').bind('click', function() {
my_function(this);
});
function my_function () {
// do stuff here on click
}
I place this code right after the AJAX call is complete.
I would add one point that was NOT obvious to me as a JS newb - typically your events would be wired within document, e.g.:
$(function() {
$("#entcont_table tr td").click(function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});
}
With event delegation however you'd want:
$(function() {
// other events
}
$("#entcont_table").on("click","tr td", function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});
If your event delegation is done within the document ready, you'll an error of the like:
cant assign guid on th not an boject

How to bind Events on Ajax loaded Content?

I have a link, myLink, that should insert AJAX-loaded content into a div (appendedContainer) of my HTML page. The problem is that the click event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. The click event is bound on DOM elements that are not loaded with my AJAX function.
What do I have to change, such that the event will be bound?
My HTML:
<a class="LoadFromAjax" href="someurl">Load Ajax</a>
<div class="appendedContainer"></div>
My JavaScript:
$(".LoadFromAjax").on("click", function(event) {
event.preventDefault();
var url = $(this).attr("href"),
appendedContainer = $(".appendedContainer");
$.ajax({
url: url,
type : 'get',
complete : function( qXHR, textStatus ) {
if (textStatus === 'success') {
var data = qXHR.responseText
appendedContainer.hide();
appendedContainer.append(data);
appendedContainer.fadeIn();
}
}
});
});
$(".mylink").on("click", function(event) { alert("new link clicked!");});
The content to be loaded:
<div>some content</div>
<a class="mylink" href="otherurl">Link</a>
Use event delegation for dynamically created elements:
$(document).on("click", '.mylink', function(event) {
alert("new link clicked!");
});
This does actually work, here's an example where I appended an anchor with the class .mylink instead of data - http://jsfiddle.net/EFjzG/
If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!
Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:
$('.parent-element').on('click', '.mylink', function(){
alert ("new link clicked!");
})
Some more reading on the subject:
https://learn.jquery.com/events/event-delegation/
http://jqfundamentals.com/chapter/events
if your question is "how to bind events on ajax loaded content" you can do like this :
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
});
so you don't need to place your configuration to every you ajax code
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
Example -
$( document ).on( events, selector, data, handler );
For those who are still looking for a solution , the best way of doing it is to bind the event on the document itself and not to bind with the event "on ready"
For e.g :
$(function ajaxform_reload() {
$(document).on("submit", ".ajax_forms", function (e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'post',
url: url,
data: $(this).serialize(),
success: function (data) {
// DO WHAT YOU WANT WITH THE RESPONSE
}
});
});
});
If your ajax response are containing html form inputs for instance, than this would be great:
$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) {
if (this.value == 'Yes') {
// do something here
} else if (this.value == 'No') {
// do something else here.
} else {
console.log('The new input field from an ajax response has this value: '+ this.value);
}
});
use jQuery.live() instead . Documentation here
e.g
$("mylink").live("click", function(event) { alert("new link clicked!");});
For ASP.NET try this:
<script type="text/javascript">
Sys.Application.add_load(function() { ... });
</script>
This appears to work on page load and on update panel load
Please find the full discussion here.
Important step for Event binding on Ajax loading content...
01. First of all unbind or off the event on selector
$(".SELECTOR").off();
02. Add event listener on document level
$(document).on("EVENT", '.SELECTOR', function(event) {
console.log("Selector event occurred");
});
Here is my preferred method:
// bind button click to function after button is AJAX loaded
$('#my_button_id').bind('click', function() {
my_function(this);
});
function my_function () {
// do stuff here on click
}
I place this code right after the AJAX call is complete.
I would add one point that was NOT obvious to me as a JS newb - typically your events would be wired within document, e.g.:
$(function() {
$("#entcont_table tr td").click(function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});
}
With event delegation however you'd want:
$(function() {
// other events
}
$("#entcont_table").on("click","tr td", function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});
If your event delegation is done within the document ready, you'll an error of the like:
cant assign guid on th not an boject

Jquery dynamically create link

I have a piece of JQuery that creates a row in a table and in one of the cells there is an X that is surrounded by a class. When it is dynamically created and then clicked on the click listener does not fire.
Here is the code.
$('#add').click(function() {
$( '#table' ).append('<td class="x">X</td></tr>');
});
$('.x').click(function() {
alert('Fired');
});
Since the <td> element does not yet exist when you register your event handler, you have to use live() or delegate() for the handler to be triggered later:
$(".x").live("click", function() {
alert("Fired");
});
$(".x").live("click", function()
{
alert("Fired");
});
Live adds events to anything added later in the DOM as well as what's currently there.
Instead of
$('.x').click(function() {
alert('Fired');
});
Change to this
$('.x').live('click', function() {
alert('Fired');
});
It binds the click function to any created element with class x
You need to use the .live function for content that's dynamically generated.
so replace
$('.x').click(function() {
with
$('.x').live('click',function() {
You are first creating the listener to all .x elements (of which there are presumably zero), then later adding new .x elements.
There are two solutions: one is to use jQuery live, the other is to rewrite your code:
var xClickHandler = function() {
alert('Fired');
};
$('#add').click(function() {
$('#table').append(
$('<td class="x">X</td></tr>').click(xClickHandler);
);
});
Use live instead of click:
$('.x').live("click", function() {
alert('Fired');
});
The html you are appending to the table has a typo, you have missed out the beggining tr tag:
$('#add').click(function() {
$( '#table' ).append('<tr><td class="x">X</td></tr>');
});
$('.x').click(function() {
alert('Fired');
});
I think you need to use the live method. http://api.jquery.com/live/
$('.x').live('click', function() {
// Live handler called.
});

run function at ready and keyup event

Is there another in jquery to run a function at page load and at a keyup event instead of the way I'm doing it?
$(function() {
totalQty();
$("#main input").keyup(function() {
totalQty();
});
});
Disregarding live or delegate optimizations, you can trigger an event like this:
$(function() {
$("#main input").keyup(function() {
totalQty();
}).filter(":first").keyup(); //Run it once
});
No need for the filter if it's not on multiple elements, just leave it out in that case.
You can use $(document).ready event to run functions on load:
$(document).ready(function(){
/* your code here */
});
Here's what I would do (jQuery 1.4+ )
$(document).ready(function() {
totalQty();
$("#main").delegate("input","keyup",function() {
totalQty();
});
});
You could use $.live(), which does event delegation, which is MUCH more efficient than created an event listener for every single input tag...and then missing any dynamically created ones. Try the following:
$(document).ready(function() {
totalQty();
$('#main input').live('keyup', function() {
totalQty();
});
});

Categories