n00b3
n00b3

Reputation: 11

Updating a global JS variable with Jquery and return that value

I need to write a function where I can set a global variable in plain js, update it's value with jQuery function and then assign that value that was updated via jQuery function into a normal javasciprt variable.

Here is the code example:

var foo; // global variable in plain js
var bar; // second global variable
jQuery(document).ready(function ($) { 

   // jquery function that updates the variable
   foo = 'updated by jquery' 

 });

bar = foo;

console.log(bar); // console should read 'updated by jquery' but it says undefined

Upvotes: 1

Views: 9550

Answers (3)

Vandesh
Vandesh

Reputation: 6904

It won't set the value to 'updated by jquery', because that update will take place when the document is ready, whereas your console.log(foo) is a part of global which will occur previously in sequence than document ready function call.

So, essentially,

var foo; // #1
$(function ($) { 
  foo = 'updated by jquery';
  console.log(foo); // output : updated by jquery //#3
});

console.log(foo); // output : undefined //#2

And the order of execution is #1, #2, #3

So, if you need the updated value, you'll need to access it at point #3 inside document .ready after it has been changed. Or you can raise/trigger an event once the value has been changed using Jquery Events like -

foo='updated';
var event = jQuery.Event( "myEvent" );
$('body').trigger(event);

// The following can now be outside of document ready
$('body').on('myEvent',function(){
   // Access updated foo value here
});

Upvotes: 2

Katana314
Katana314

Reputation: 8620

Your code actually should work correctly. But if we use the comments as markers in order (so #2 = "//jquery function that updates the variable"), keep in mind it'll run in the order [#1, #3, #2] because the ready() function will run after the others when the document is ready.

As long as any code that needs foo is running after your ready function, it should read it correctly.

Upvotes: 0

Murali Murugesan
Murali Murugesan

Reputation: 22619

Because you are updating the foo only on ready event but you are tying to log before ready fires

Try this

jQuery(document).ready(function ($) { 
// jquery function that updates the variable
  foo = 'updated by jquery';
  console.log(foo);
});

Upvotes: 3

Related Questions