I am using jQuery to apply some UI effects like adding a class to a number of elements, in the JS file i use :
$('.dataGrid').each(function(){
$(this).find('tr:odd').css('background-color', '#F7F8FA');
});
but when i use ajax to load an element with the class .dataGrid the rules up there doesn't apply, my solution was to make a function joins all cases like this one and call it every time i make an ajax request ! .. this off course is not a pro one .. i found .live() , i used and it worked fine with events like :
$('dataGrid').live('moveover', function(){ ... }); .
the .live solution is very good with events ... is there any way to use the same concept with the effects like mentioned up there ? ... i mean a way to reapply the rules set before, every time a change takes place on these elements ( adding new one for example )
I wish i was clear enough, Thanks in advance :)
The Livequery-plugin supports triggering functions when new nodes are added to the DOM.
Something like this should work:
$('.dataGrid').livequery(function() {
$(this).find('tr:odd').css('background-color', '#F7F8FA');
}
Depending on how you are loading elements i.e. which AJAX technique you are using, you can achieve this in many ways. If you are using jQuery Ajax then you can use the jQuery.when method.
Basically with this method you can have deferred execution. You can say something like "when the ajax call completes then do this function". The syntax goes like
$.when( $.ajax("test.aspx") ).then(function(ajaxArgs){
alert(ajaxArgs[1]); /* ajaxArgs is [ "success", statusText, jqXHR ] */
});
Following link will give you more information
http://api.jquery.com/jQuery.when/
Since you are using ajax to append your .dataGrid elements you could register a handler for ajaxComplete() that will handle the application of your :odd class.
$(document).ajaxComplete(function() {
$('.dataGrid').each(function(){
$(this).find('tr:odd').css('background-color', '#F7F8FA');
});
});
Related
I'm using the select2 jQuery plugin (V4) and from what I can see they don't have an onInitialized event; but I need to run some code after it has been initialized.
By Initialized I mean that it has completed and that all elements associated to it are now ready.
I seen this question, but none of the answers seem to address the issue of continually checking until it becomes available; like what if it's not there the first time you check, then the code you needed to run wouldn't run.
I thought of using setInterval with something like the above but wasn't sure if there was a better way?
The only way you can go async it's when you fetching remote data, so you can inject you callback in that ajax.
If you have several ajax calls use deferred:
var deffered1 = $.Deferred();
In your ajax calls after success and error use the following code to resolve those calls.
complete:function(){
deffered1.resolve()
}
And to subscribe for events:
$.when(deffered1, deffered2).done(function() {
// your initialized actions
})
If you have more than 1 select elements on your page which needs to be converted to select2 dropdown then you can use the following: Multi Select version
if you have just a single select on the page, you can go with the following:
Single Select option:
Hope it helps.
It's for a backbone application,
I'm using Jquery html() function to insert my views templates into the layout everywhere, and I would like to be able to trigger an event each time the html() function of jQuery is called to check the html of the page.
Is there a way to do that ?
( Like App.on('html', blablabla...); )
Thank you !
As Marc B suggested DOM MutationEvents is available on some browsers (not many). By default jQuery does not fire any event when using html, but you can define your own behaviour for this, for example:
(function($) {
var html_ref = $.fn.html;
$.fn.extend({
html : function() {
$(document).trigger( 'html_change' );
return html_ref.apply(this, arguments);
}
});
})($);
It should work, didn't test it though. You can use the same with .text method. Now you can simply use:
$(document).bind( 'html_change', function() {
// Hurray! Html changed!
});
That's the idea, use it as you wish.
AFAIK, the jQuery html() method doesn't fire any subscribable events per se, but you could probably roll your own implementation of a simple Observer pattern. I use this across a large number of projects and it provides a great, clean, lightweight way to encapsulate arbitrary event handling across loosely-coupled modules.
However, this is presuming that you have programmatic control over every time the html() method is called - if not, then this would be more difficult, as there is no callback function to hook into.
I'm loading part of my webpage using AJAX, in particular jQuery.load(). With this the usual jQuery pattern
$('.classname').click(...) // Handler
// or, working with bootstrap
$("a[rel=tooltip]").tooltip() // Function
or similar obviously don't work any more, because they are called only when the page is loaded. I realize there is jQuery.on for the first example, but how would I implement the second?
Is there a simple (builtin) way to also apply these to jQuery.loaded stuff, or do I have to work around it myself? Seems like a problem a lot of people should be having.
You have to work around it yourself; but you can easily to this by calling $("a[rel=tooltip]").tooltip() in the callback for load():
$('#blah').load('/somewhere.html', function () {
$('#blah').find('a[rel="tooltip"]').tooltip();
});
Be sure to restrict the tooltip() call to only newly loaded elements, or you'll end up initializing tooltip multiple times per element (which may result in weird behaviour).
To avoid duplicating code you just need to define a helper function;
function initTooltip(root) {
return $(root || document).find('a[rel="tooltip"]').tooltip();
}
Which allows you to init tooltip. The parameter is optional, and lets you restrict initialization to only descendants of the provided element, e.g.:
jQuery(document).ready(function ($) {
initTooltip(); // equivilant to initTooltip(document);
$('#blah').load('/somewhere.html', function () {
initTooltip('#blah');
});
});
I'm authoring a jQuery plugin in which one of the methods that I'd like to write will not take a selector argument and does not need to pass an element. I'd like it to be available by a call like $.myMethod() like the built in $.ajax() method. Up to now I've tried something like
$.fn.myMethod(options) {
console.log("I've been called");
}
This works when I try $('.a_selector').myMethod() but not when I try $.myMethod().
Is this doable with a jQuery plugin or is it only available for interal functions.
The purpose of this method is to perform an action on some data that is stored in jQuery.data. I recognize that they jQuery.data is associated with an element, but in this case I've hard coded it to the body element to make things easier for the end user.
The functions that are members of $.fn apply to jQuery objects, not to the $ object itself. If you want to create such a method, you only have to write:
$.yourMethod = function() {
// Do something.
};
Now you can call it without a jQuery object:
$.yourMethod();
An elaborate way of declaring such a function can be
$.extend({myMethodA:function(){
//Do something
},
myMethodB:function(){
//Do something else
}
});
Does anybody know how to execute javascript functions in an html that is loaded via ajax? I mean the html contains both plain text and javascript. In my case it seems that only the in-line javascript (eg. onclick="dosomething();return false") gets executed. The pre-defined functions which are wrapped by < script language = "javascript >are unfortunately ignored..
i have search couple articles through the site but the results are either use getScript to load a pure js or use eval. please help me out of this! Thank you very much!
File 1:
<script type="text/javascript">
function test() {
alert('i got loaded dynamically!');
}
</script>
File 2:
$.get('file1.html', function(html) {
$(document).append(html);
test(); // alerts "i got loaded dynamically!"
});
See it in action.
According to the doco, if you use $.ajax and specify a data type of "html", included script tags are evaluated when inserted in the DOM. Make sure your server is returning the correct data type, see Specifying the Data Type for AJAX requests for more info
If that doesn't help, Artem's approach also works well, providing you only make the request once. If you are making the same $.get call over and over, you'll end up with multiple copies of yourFunctionCall in the head, and Strange Things will happen :-)
Look up jquery event delegation, and the .live() method.
http://docs.jquery.com/Events/live#typefn
Event delegation is especially useful and efficient if you're working with a large piece of html that you've added dynamically.
I don't know if this fixes your problem... but if your loaded html also includes a link to jquery's code base, it can cause issues with the child-code not correctly linking with the handle to the jquery object ($).
If I understand you correctly, you receive from your AJAX call plain HTML mixed with javascript code, e.g. with tags. I'm didn't checked it, but you can try to do the following:
$.get( ajaxURL, function( data)
{
$( "head").append( $( data).find( "script"));
yourFunctionCall( );
});