I have a JQuery plugin function where I would like to assign selectors from an iframe just once, and then use them throughout the plugin.
In the basic example below, if I have a function within the plugin it won’t work for the $modal selector unless I explicitly set it within the function.
Is there any way to do this so that I can assign the selector to a variable just once and have it accessible throughout the plugin function?
jQuery.customPlugin = function() {
var $modal = $('#modal', frames['admin-bar'].document);
$('#hide-modal').click(function(){
hide_modal();
});
// doesn't work - but I want it to somehow
function hide_modal(){
$modal.hide();
}
// works, but requires lots of re-querying if I have lots of selectors/functions
function hide_modal(){
var $modal = $('#modal', frames['admin-bar'].document);
$modal.hide();
}
});
jQuery selectors query the DOM when you instantiate them. In other words, if you do
var $foo = $('.bar'), and then add a new element with class “bar” to the page, your $foo variable won’t include it. This is just how jQuery works.What you can do is write a method get$Modal, which re-queries every time you run it. For instance:
Alternatively, what you can also do is “register” your modals as you create them, avoiding the need to re-query. Something like:
That should work great if you have a common place where all modals are created. If you create modals in many different places, you might want to use a custom event to organize things: