mxlnge
mxlnge

Reputation: 51

Update function because variable value changed?

is it necessary to update a function on a changed variable? I don't know how to explain this correctly but i'll try my best in the following.

I have a .click() function which gets initialized if the document is ready. Inside of this function is a .animate() function which uses a variable (var content) as selector. This variable is also defined if the document is ready. (Below you see a simplyfied version of the code)

$('.selector').click(function () {
   $(content).animate({
       scrollTop: target.offset().top
   }, 1000);
   return false;
});

But this variable changes between two values according to the viewport width. (Below you see a simplyfied version of the code)

if(viewportWidth < 768){
    content = $('.content-wrap');
}else{
    content = $('html, body');
}

So if the variable value is changing, do I have to update or reinitialize my function? Because it'not working for one of the selectors.

Thanks for any help or any food for thought. :)

=============UPDATE=============

Okey, it's still not working like expected.

$(content).scroll(function() {
    console.log($(this));
}

This doesn't work if the value of the variable (content) changed. It's only working for the value which is set for this variable if the document is ready.

Upvotes: 2

Views: 438

Answers (2)

Pradeep Kumar Das
Pradeep Kumar Das

Reputation: 891

you already define the variable as selector so no need to write $(content) you can write below code to execute properly.

if(viewportWidth < 768){
 content = $('.content-wrap');
 content.animate({scrollTop: target.offset().top}, 1000);
}else{
 content = $('html, body');
 content.animate({scrollTop: target.offset().top}, 1000);
}

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337570

You don't have to change anything within your function as the value of content will be read at the point the click event happens.

What you have will work absolutely fine, so long as the content variable is defined within scope of both locations in your code base.

You should note that content itself will be a jQuery object, so you don't need to wrap it again in the click handler; just content.animate({... will work fine.

Upvotes: 1

Related Questions