vbotio
vbotio

Reputation: 1674

variable used out of scope

I'm doing a responsive background video. I have this code.

<video id="bgvideo" />

function scaleVideo() {

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();

    var videoNativeWidth = $('video#bgvideo')[0].videoWidth;
    var videoNativeHeight = $('video#bgvideo')[0].videoHeight;


    var heightScaleFactor = windowHeight / videoNativeHeight;
    var widthScaleFactor = windowWidth / videoNativeWidth;


    if (widthScaleFactor >= heightScaleFactor) {
        var scale = widthScaleFactor;
    } else {
        var scale = heightScaleFactor;
    }

    var scaledVideoHeight = videoNativeHeight * scale;
    var scaledVideoWidth  = videoNativeWidth * scale;

    $('video#bgvideo').height(scaledVideoHeight);
    $('video#bgvideo').width(scaledVideoWidth);
}

I'm using grunt to compile my code and etc. Jshint of grunt is saying I'm using "scale" out of scope and I cant understand why.

Any suggests ?

error

Upvotes: 5

Views: 8388

Answers (2)

Venkata Krishna
Venkata Krishna

Reputation: 15112

You should not write var scale = heightScaleFactor; inside the else statement if you want to use it outside of it.

Initialize scale outside the if

 var scale;
 if (widthScaleFactor >= heightScaleFactor) {
     scale = widthScaleFactor;
 } else {
     scale = heightScaleFactor;
 }

Upvotes: 6

user2516837
user2516837

Reputation:

Try this instead:

function scaleVideo() {
    var scale; //this is the change

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();

    var videoNativeWidth = $('video#bgvideo')[0].videoWidth;
    var videoNativeHeight = $('video#bgvideo')[0].videoHeight;


    var heightScaleFactor = windowHeight / videoNativeHeight;
    var widthScaleFactor = windowWidth / videoNativeWidth;


    if (widthScaleFactor >= heightScaleFactor) {
        scale = widthScaleFactor; //simply modify the value here
    } else {
        scale = heightScaleFactor;
    }

    var scaledVideoHeight = videoNativeHeight * scale;
    var scaledVideoWidth  = videoNativeWidth * scale;

    $('video#bgvideo').height(scaledVideoHeight);
    $('video#bgvideo').width(scaledVideoWidth);
}

Upvotes: 2

Related Questions