jQuery execute code on future DOM objects?
So here's the question:
I'm using jQuery to target DOM elements and set their heights based on the height of the browser window, parent elements, etc. Here is an example:
$('.multiPanelContainer .panelContainer').each(function() { $(this).css('height', document.body.offsetHeight - $(this).offset().top - 13 + 'px') })
This is working fine except when AJAX calls introduce new DOM elements after page ready. I have used live() before to bind event handlers to new DOM elements but all that I want to do here is manipulate the css of the new elements. Is there a way to have the above code called on future matches of the jQuery selector? I could bind the jQuery to the AJAX postback on the back-end of the application, just wondering if there was an easy front end solution.
Here's the background:
This whole situation is less than ideal. I'm working with an existing ASP.NET application that was written targeting IE6/IE7 and makes extensive use of IE css 'expression()' statements. I didn't make that decision so don't blame me. Anyway, now the application owners want to be able to use the app in Chrome, which doesn't understand said selectors. The quick and dirty solution my director recommended was to convert the statements into the jQuery statements you see me using above and include those in a single js file linked in the master page. I think splitting the design into css and js pieces is going to be bad for maintainability but I only have so much cont开发者_StackOverflow社区rol here.
You will have to re-execute the code once the DOM changes. You can save energy by tagging those already done with a new classname so you can skip over them.
I think you can use the live() handler like this. Thought I have not done it in a long time.
$('.multiPanelContainer .panelContainer').live("load", function(e){
// do your CSS change here.
})
You could attach a custom event to the containing element (for example the body tag) and trigger that event whenever you want it (ajax call or anything else that you might want...).
BTW, why not use a regular function instead of an anonymous one and just invoke it on the new elements that you create with ajax?
$(document).ready(function() {
do();
$(document).ajaxComplete(function() {
do();
});
});
function do () {
$('.multiPanelContainer .panelContainer').each(function() {
$(this).css('height', document.body.offsetHeight - $(this).offset().top - 13 + 'px')
})
}
It's executed every time an Ajax-Request has been completed
精彩评论