AmintaCode AmintaCode - 2 months ago 9
jQuery Question

How to update some global variables used in 'scroll' event when 'resize' event is fired in JQuery / Javascript?

I have some variables globally declared:

var a = $('.ela');
var b = $('.elb');
var top_a = $('.ela').offset().top;
var top_b = $('.elb').offset().top;


I use these variables on "scroll" event applied to the
<main>
element:

$('main').on('scroll', function(top_a, top_b) {
// do something with top_a and top_b
}


Now, I need to use the updated values of these variables at the event $(window).resize(), so I write:

$(window).resize(function() {
top_a = $('.ela').offset().top;
top_b = $('.elb').offset().top;
})


This way the global variables are updated, but in $('main').on('scroll', function etc) I get the old values...

Where am I doing wrong?

Answer

You are not passing the variables to scroll event at

$('main').on('scroll', function(top_a, top_b) {
// do something with top_a and top_b
})

top_a would reference the event object, not top_a variable.

You can pass the variables using event.data

$('main').on('scroll', {top_a:top_a, top_b:top_b}, function(event) {
   // do something with top_a and top_b
   console.log(event.data.top_a, event.data.top_b)
});

or, directly by referencing the variables

$('main').on('scroll', function(event) {
   // do something with top_a and top_b
   console.log(top_a, top_b)
});