Skip to content

Instantly share code, notes, and snippets.

@jfirebaugh
Created May 4, 2012 18:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfirebaugh/2596712 to your computer and use it in GitHub Desktop.
Save jfirebaugh/2596712 to your computer and use it in GitHub Desktop.
$(<selector>).ready() -- a nice syntax for page-specific script
/*
With the Rails asset pipeline, you usually include the JS for
your entire application in one bundle, but individual scripts
should be run only on certain pages. This extends jQuery's
.ready() to provide a nice syntax for page-specific script:
$('.posts.index').ready(function () {
// ...
});
This works well if you include the controller name and action
as <body> element classes, a la:
http://postpostmodern.com/instructional/a-body-with-class/
The callback will be run once for each matching element, with
the usual 'this' context for a jQuery callback. `$(fn)`,
`$(document).ready(fn)`, and `$().ready(fn)` behave as normal.
*/
(function ($) {
var ready = $.fn.ready;
$.fn.ready = function (fn) {
if (this.context === undefined) {
// The $().ready(fn) case.
ready(fn);
} else if (this.selector) {
ready($.proxy(function(){
$(this.selector, this.context).each(fn);
}, this));
} else {
ready($.proxy(function(){
$(this).each(fn);
}, this));
}
}
})(jQuery);
@faragly
Copy link

faragly commented Jun 16, 2016

В связи с обновлением jquery до 3.0 версии, вышеуказанный плагин теряет актуальность.

(function ($) {
    $.fn.selectorReady = function(fn) {
        $($.proxy(function() {
            $(this).each(fn);
        }, this));
    };
})(jQuery);

http://codepen.io/faragly/pen/RRRLdQ

@stopanko
Copy link

Thanks A lot !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment