3 ms·
could somebody please post an example to point #1?
by mildweed 16y ago
could somebody please post an example to point #1?
- niyazpk 16y agoInstead of: $(document).ready(handler); you can write: $(handler);
- kilian 16y agocommonly used like this: $(function() { // write the stuff you normally put in $(document).ready( ... ); });
- niyazpk 16y agoJust in case anyone finds it useful, use this when you have to mix jQuery with other JavaScript libraries like prototype: jQuery(function($) { // your code using $ }(jQuery)); This way you can use $ to reference jQuery in your code even if the other library took control of $ in the global scope.
- misterbwong 16y agoWe went with jQuery in no conflict mode when we needed to mix jquery and the prototype lib for ads. from the docs: var j = jQuery.noConflict(); // Do something with jQuery j("div p").hide(); // Do something with another library's $() $("content").style.display = 'none';
- davecardwell 16y agoYou don’t need that jQuery parameter (in fact, I think that makes it invalid JavaScript). ie. jQuery(function($) { // your code using $ }); You might be thinking of the recommended method of creating a closure, in which the code is executed immediately rather than upon page load: (function($) { // your code using $ })(jQuery);
- stanleydrew 16y agoIt's not invalid JavaScript, and it does work, but it isn't doing exactly what he thinks it's doing. You need the jQuery parameter to make sure the $ in your code refers to the jQuery object and not something else. Without it your code is just referencing the global $ object which some other framework could have poached for itself. But I suspect you already know all that. What his code is actually doing is creating an anonymous function intended to provide a safe place for $-based code, evaluating it immediately, and then passing the return value to the jQuery function. Depending on the return value this may be useful or not, but I'm pretty sure it's not what he intended. His function is evaluated immediately rather than when the DOM is ready. What you want to do is combine the second part of your example with your already-written code: (function($) { $(function () { // your code to fire when the DOM is ready }); })(jQuery);
- niyazpk 16y agoYou are correct. That was a mistake from my part.
- brown9-2 16y agoThe article should really note that the latter is just an alias for the former. It reads as if the author is trying to say that the reason for using $(document).ready(handler) - to wait to run certain functions until the entire DOM has loaded - is no longer necessary.