Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Variable Jquery

Tags:

jquery

I've asked this question before but never actually got it working.

More or less, I have multiple JS files, that I need to check against the one variable. I have a function that checks to see if a class exists and then changes the variable.

var states = function(){

    if($('#Animation.switch.switchOff').length == 1){
        animationtoggle = 0;
    }
    else {
        animationToggle = 1 ;
    }
    if($('#Autoscroll.switch.switchOff').length == 1){
        scrolltoggle = 1;   
    }
    else {
        scrolltoggle = 0    
    }
    return {
        animationtoggle: animationtoggle,
        scrolltoggle: scrolltoggle
    };
}

I then have inside another function, in another JS file this:

Okay, I've done this, although It still doesn't fix my problem of being able to use this variable on another file, I have this inside the function: 

$(function() {
    var ss = states();
    ss.animationtoggle;
    var last_position = 0;
    var duration = 300;
    if (animationtoggle == 1){
       //only do something if it's equal to 1 "on"
});

And this is the toggle button code:

$('#optionMenu ul li').click(       
function() {
$(this).toggleClass('switchOff');
var ss = states();
ss.scrolltoggle;
ss.animationtoggle; 
});

Am I approaching this the right way?

Please help! Here's my site, the toggle is up the right hand corner at the moment :http://shannonhochkins.v5.cloudsvr.com.au/

like image 987
Shannon Avatar asked Jan 26 '26 12:01

Shannon


1 Answers

I believe you are overwriting them by creating and assigning the same variable multiple times. The global variables should be defined once outside the scope of your specific function, preferably close to the first operation on page load. Global variables are assigned to the window object and can be accessed by name once declared.

//You need to define your global variable out of the scope of your function
var ss = states();

$(function() {
if (ss.animationtoggle == 1){
   //only do something if it's equal to 1 "on"
});

$('#optionMenu ul li').click(       
function() {
$(this).toggleClass('switchOff');
//Don't create the same variable here with the same name
//Instead access the global variables by using them
// ss.scrolltoggle;
// ss.animationtoggle; 
});
like image 190
Matt Avatar answered Jan 28 '26 02:01

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!