0

can you help me please... How to return variable from jquery function

var height = $(window).height();

$(window).resize(function(){
    var height = $(window).height();
    return height;
});

setInterval(function() {
    $('div').append( 'Index: ' +  height );
}, 500);

3 Answers 3

5

You don't need to return. Try this:

var height = $(window).height(); // define "height" here

$(window).resize(function(){
    height = $(window).height(); // update "height" variable, 
                                 // don't user "var" here.
                                 // because using "var" will redefine
                                 // "height" again and no longer contain the
                                 // updated value on window resize 
                                 // out of this resize function scope
});

setInterval(function() {
    $('div').append( 'Index: ' +  height );
}, 500);
Sign up to request clarification or add additional context in comments.

Comments

2

When you use var you're creating a new variable, not overwriting the original. You'll want this instead:

var height = $(window).height();

$(window).resize(function() {
    height = $(window).height();
});

// ...

Comments

0

I suppose the answer to your question depends on how you want to return it. Console? Alert? A div or other element? See below for a list.

  • console.log(height)
  • alert(height)
  • $("#elementID").html(height); // or whatever selector and method work for your case

I suppose you could also convert that $(window).resize block into a function, then call that function. That should work, too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.