Calling a function to reference variables

   $( document ).ready(function() {
   
    function geteverthing() {
        var fonttype = $('#font').attr('class');
        var sizetype = $('#size').attr('class');  
        var colourval = $( "#colourselect option:selected" ).val();
        var imageval = $( "#imageselect option:selected" ).val();
       }
       
    function imageupdate() {    
       geteverthing();      
       // Do some stuff with these variables
       }
       
    function colourupdate() {    
       geteverthing();      
       // Do some stuff with these variables
       }  
       
     function fontupdate() {    
       geteverthing();      
       // Do some stuff with these variables
       }   
       
    }); 

I have several functions which use the same variables. The variables change value depending on what functions are called when using a form.

In the previous set up I had the variables called within each function and everything worked fine.

I then tried to bring the variables outside all the functions within document ready. This resulted in calling variables which weren’t up to date when interacting with the form.

I then tried to put the variables in another function and call that function within each of the other functions but I get a variable not defined.

For cleanness I want to only have these variables defined once and reference them, can someone tell me what I am doing incorrectly?

Thanks for your time.

You need to return them from the function where they are defined so that they can then be accessed from outside of that function in the subsequent code.

For example:

function geteverthing() {
        return { fonttype : $('#font').attr('class'),
                   sizetype : $('#size').attr('class'),  
                   colourval : $( "#colourselect option:selected" ).val(),
                   imageval : $( "#imageselect option:selected" ).val()
                   };
       }

function imageupdate() {    
       var o =geteverthing();      
       // Do some stuff with these variables
       console.log(o.colourval); // example of how to reference
       }
1 Like

Worked perfectly, thank you so much! :smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.