Ulterior
Ulterior

Reputation: 2912

Unable to access javascript property

I have a javascript code to bind a jQuery colorbox to my element, but cant figure out how to change the value of the property inside the callback:

$(".iframe").colorbox({
    iframe: true, 
    width: '80%',
    height: '80%',
    onLoad: function() {
        console.log(width);
    },
});

Why do I get ReferenceError: width is not defined or how do I access this property?

Upvotes: 0

Views: 94

Answers (4)

Ulterior
Ulterior

Reputation: 2912

I was able to achieve what I want by using the:

width: function() {

}

this way I can programmatically override the width variable, which I was trying to do...

Upvotes: 0

lante
lante

Reputation: 7346

Write this in your onLoad function:

onLoad: function() {
    console.log($(this).width());
}

Upvotes: 0

Mike Cluck
Mike Cluck

Reputation: 32531

You're attempting to access a width variable in the global scope. Sort of like trying to use document, window, or $. What you want to access is the width property of the colorbox object. If the plugin binds this to the colorbox object then you could do something like this:

$(".iframe").colorbox({
    ...
    onLoad: function() {
        console.log(this.width);
    }
});

But I assume you're trying to access the width of the element you're binding the colorbox to. If that's the case, you may try something like this:

var $iframe = $(".iframe");
$iframe.colorbox({
    ...
    onLoad: function() {
        console.log($iframe.width());
    }
});

Upvotes: 0

hugomg
hugomg

Reputation: 69994

You get an error because width is just a property of the object you are passing to the colorbox function. Its not a variable you can reference.

They doing this:

var myWidth = '80%';

$(".iframe").colorbox   ({
    iframe:true, 
    width: myWidth,
    height:'80%',
    onLoad:function() {

        console.log( myWidth );   

    },
});

or this

var props = {
    iframe:true, 
    width: '80%',
    height:'80%',
    onLoad:function() {

        console.log( props.width );   

    },
};

$(".iframe").colorbox(props);

Upvotes: 1

Related Questions