jquery .on() not working after .load() of php file - ajax

I'm attempting to run the following simple bit of code on an html snippet contained in a php file, loaded with jquery's .load() function:
$(".thumbnail").on("click", function(event){
alert("thumbnail clicked");
});
However, I can't seem to get it to work on this portion of my page. I have other calls to elements not loaded via ajax and they work fine with the .on() function. I was under the impression that .on() would recognize ajax loaded content.
My .thumbnail elements are pictures in img tags contained within a series of divs all loaded via ajax, jquery can't seem to find any of this content. All of my code is contained within the ready function.
Is there a way to get jquery to recognize these new elements?
Thanks.

You need a delegated event handler for dynamic content :
$('#container').load('somefile.php');
$('#container').on('click', '.thumbnail', function(event){
// do stuff
});
The closest non-dynamic parent would probably be the element you're loading the content into, and you need to attach the event handler to that element, filtering based on the .thumbnail class, like the code above.

Related

Reload javascript after thymeleaf fragment render

I have javascript files defined in the <head> of both my layout decorator template and my individual pages which are decorated. When I update a thymeleaf fragment in one of my pages the javascript defined in the head of the parent page no longer works. Is there a standard way to 'refresh' these js files?
Thanks.
Additional clarification :
I have a form submitted by an ajax call which updates a table in the page. I have a Jquery onClick function targeting a button in the updated table. The javascript doesn't seem able to bind to the returned elements in the updated part of the page. I select by element class and can see that the selection works prior to the partial fragment render.
For me it is unclear what you mean by
javascript defined in the head of the parent page no longer works.
The page is created on the server. Normally it contains urls of the javascript files
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
In this case 'refreshing' the javascript files can happen only in the client.
Check the html of the page in the client.
Are the tags as expected ?
Are there tags for all expected javascript files ?
With the browser tools (for example Google Chrom developer tools ) check that all script files are actually loaded.
If this doesnt help, it could be that the order of the script tags has changed between the first and second load. This could cause a different behaviour of the javascript executed in the browser.
EDIT :
With the initial load you bind javascript callbacks to dom elements.
You do this directly or through Jquery or other libraries.
When a new dom element is loaded, it has no callbacks bound to it, even if it has the same id as a replaced dom element.
So after the load you have to bind your callbacks again.
If you bound them 'by hand', just bind it again.
If you are using a JQuery plugin, that made the bindings, look into the code or documentation, many of them have a function for that or you can call initialization again.
Once you added new content to the DOM you need to bind again the new content.
Let's say I have a button with some class, the event in binded to the class:
<button class="someclass">Button 1</button>
<script>
var something = function() {
// do something
};
$(".someclass").on("click", something);
</script>
If I add more buttons from the same class to the DOM, they will have not have the click event binded. So once you load the new content via ajax, also remove all binding and add again (you need to remove or you will have buttons with 2 events).
$(".someclass").off("click");
$(".someclass").on("click" , something);

jQuery load() event not firing after loading content via AJAX

I have some code which does the following:
External content is loaded via AJAX (video thumbnail images)
The new content is then inserted into a div using $("#content").append();
A mobile touch scrolling helper (iScroll) is applied to this div.
However the jQuery "load" event is not firing when the DOM changes due to an AJAX event, which means the call to initialise the scroller is happening too soon (before the images inthe content has loaded) which means it often doesn't get intiiallised. Without waiting for the images to load the content box is often short enough such that a scroll function isn't needed, but then when the images subsequently load, the box is not scrollable.
$("#videoList").append(videoThumbnails);
$(document).load(function () {
// doesn't fire
initScroller();
});
It appears that jQuery's append function does not block until all images referenced in the appended HTML have loaded.
How can I detect that all of the images loaded by the AJAX function have finished loading in order to call the initScroller() function AFTER all images have loaded?
OK I've found the solution in another similar question. It turns out there's a jQuery waitForImages plugin which does exactly what I want:
So I can just do this:
$("#videoList").waitForImages(function () {
// Fires when all images in the #videoList div have loaded
initScroller();
});
The methods you are trying to use are triggered only once, when the page is loaded, but not for changes you make to the DOM aftewards (e.g. inserting content with ajax).
If you want to observer DOM changes you can use the DOMNodeInserted event
$(document).bind("DOMNodeInserted", function(event) { ....do stuff...here });
But generally it would be better to trigger this with the ajax callback.
$('#targetElementForYourContent').load('server/url.html', function() {
...do stuff here....
});

Using jQuery Plugins with live()

I have a page that dynamically loads content with the jQuery load() function, so I need to use live() for each of my jQuery functions on this page. However, I am unable to get live() to work with jQuery plugins. For example, I want to use jQuery accordion:
$("#accordion").accordion();
But I cannot find the right syntax to get accordion to work with live(). I have tried:
$("#accordion").live("load", accordion());
$("#accordion").live("load", $("#accordion").accordion());
$("#accordion").live("load", $(this).accordion());
I either receive the "b is undefined" error, or "accordion is not defined."
You must use anonymous function
$("#accordion").live('load',function(){
$(this).accordion();
});
Edit:
If the accordion is already in the page when you first render it, then you shouldn't call it using live(), but by page load
$(function(){
$("#accordion").accordion();
});
This could partly answer your question:
I would suggest using livequery instead to do this:
$("#accordion").livequery(
function() { $(this).accordion(); },
function() { $(this).accordion("destroy"); }
);
The first function will initialize jQuery UI's accordion functionality on any $("#accordion") element that's added to the DOM, and the second one will destroy the accordion object when that same element is removed from the DOM.

jQuery: Can I automatically apply a plug-in to a dynamically added element?

I'm in the process of converting my web app to a fully AJAX architecture.
I have my master page that is initially loaded and a div container that is loaded with dynamic content.
I created a few jQuery plugins that I apply to certain elements in order to extend their functionality. I'd normally call the functions as follows during each page load:
$(document).ready(function () {
// Enable fancy AJAX search
$(".entity-search-table").EntitySearch();
});
This would find the appropriate div(s) and call the plugin to enable the necessary functionality.
In an AJAX environment I can't just apply the plugin during the page load since elements will be added and removed dynamically.
I'd like to do something like this:
$(document).ready(function () {
// Enable fancy AJAX search
$(".entity-search-table").live("load", function () {
$(this).EntitySearch();
});
});
Question: Is there any way that I can trigger an event when a <div> or other element that matches a selector is added to the DOM?
It seems incredibly wasteful to activate the plug-in every time an AJAX request completes. The plug-in only needs to be applied to the element once when it is first added to the DOM.
Thanks for any help!
Yes - take a look at liveQuery. Example:
$('.entity-search-table').livequery(function(){
$(this).EntitySearch();
});
It seems incredibly wasteful to activate the plug-in every time an AJAX request completes. The plug-in only needs to be applied to the element once when it is first added to the DOM.
You can get the best of both worlds here, for example:
$("#something").load("url", function() {
$(".entity-search-table", this).EntitySearch();
});
This way it's only applying the plugin to the .entity-search-table elements you just loaded, since we specified a context to $(selector, context) to limit it.
The DOM 2 MutationEvent is what you really want, but unfortunately it isn't supported by IE. You'll need to either use live()/ delegate() binding in the plug-in, or (as I did when I had to work around this) use callbacks from your AJAX loaders indicating the scope of what has changed.
Use the live binding in your plugin code directly
jQuery.fn.EntitySearch = function() {
this.live(..., function(){ your plugin code });
return this;
}

JQuery - Ajax return HTML wont allow further Jquery functions?

Kinda New to Jquery and hit an issue regarding returned HTML. I am using the .load() function to load HTML returned from a jsp file - its all working grand except the returned HTML doesnt seem to allow further Jquery functions to be called on it.
i have a click and toggle combination running for "#showgame" - this id is in the returned HTML but clicking on it does nothing when it should. Do i have to update anything to tell jquery that this id now exists on the page after load() call?
Regards,
Cormac
You need to use the live() function to bind the click event.
$("#myelement").live("click", function() { });
Live binds the event to current and future elements that match the selector.
Read more at http://api.jquery.com/live .

Resources