Marty Trenouth
Marty Trenouth

Reputation: 3752

Passing Parameters to jquery ready handler

I would like to create a single function to automate htmlwireups. Some portions of the page are loaded using ajax and I would like to call a single function to ready both the document and the lazily loaded sections.

Example:

function WireHtml(target){
    $(target).ready(function(target){

        // call anything you would normally wire in a standard ready
        // but only on the descendants of the target node such as wiring up
        // an accordion
        $(target).find(".accordion").accordion();

    }
}

Upvotes: 0

Views: 895

Answers (1)

jball
jball

Reputation: 25014

Simply pass the target variable through to the inner function without referencing it in the jQuery ready call.

function WireHtml(target){
    $(function(){ // <- note the lack of "target" references

        // call anything you would normally wire in a standard ready
        // but only on the descendants of the target node such as wiring up
        // an accordion
        $(target).find(".accordion").accordion();

    });
}

The target variable will be available within the function that's attached to the ready handler due to a closure.

Side note, $(document).ready(yourFunction) or $(yourFunction) are preferred to $().ready(yourFunction), though they are all equivalent.

Upvotes: 2

Related Questions