Max
Max

Reputation: 259

How to pass a jQuery variable to a plugin property?

Sorry I'm beginner, can somebody help me out?

<script>
var iW = $(document).width();

$(function() {
//single book
$('#mybook').booklet({
   next: '#custom-next',                
    prev: '#custom-prev',
     keyboard: true,
    width:   return iW, // here is the problem! It doesn't work.
    height: 200

});

//multiple books with ID's
$('#mybook1, #mybook2').booklet();

//multiple books with a class
$('.mycustombooks').booklet();

});

</script>

Upvotes: 2

Views: 708

Answers (3)

Rup
Rup

Reputation: 34408

As above, you don't need the return.

But alternatively many plugins will accept functions for their parameters to evaluate when needed so you could e.g.

$('#mybook').booklet({
    next: '#custom-next',
    prev: '#custom-prev',
    keyboard: true,
    width: function() { return $(document).width(); },
    height: 200
});

I don't know that plugin so I'm not 100% sure it'll support it, but many do.

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237865

return there is unnecessary. You just need width: iW.

That said, you should also bring the call to $(document).width() within the ready block.

$(function () {
    var iW = $(document).width();

    //single book
    $('#mybook').booklet({
        next: '#custom-next',
        prev: '#custom-prev',
        keyboard: true,
        width: iW,
        height: 200

    });

    //multiple books with ID's
    $('#mybook1, #mybook2').booklet();

    //multiple books with a class
    $('.mycustombooks').booklet();

});

Upvotes: 4

T.J. Crowder
T.J. Crowder

Reputation: 1074355

You're really close. Just ditch the return, e.g.:

$('#mybook').booklet({
   next: '#custom-next',                
    prev: '#custom-prev',
    keyboard: true,
    width:   iW, // <=== Updated
    height: 200

});

That will use the value of iW as of the time you call booklet.

Within an object literal (that's the { ... } thing that you're passing into the booklet function), property initializers are a lot like assignment statements. The bit on the left before the : gives the property name (and cannot be an expression), and the bit on the right after the : gives the value for the property (and can be an expression — a simple variable name, a function call, etc.).

Upvotes: 5

Related Questions