Search code examples
javascriptjqueryglobal-variablessequences

Storing 2 numbers in a sequence


I need to store 2 variables. They represent the order they were pressed in. For example "tab2" with value 2, and after that the "tab1" with value 1 etc.

I tried to store them with

  window.ACTIVE_NUMBER;
  window.LAST_NUMBER;

and some global functions, but It's always telling me that LAST_NUMBER is undefined.

Is there perhaps an easier way, like with tables?

I need the data from the clicks to animate some stuff later on. If the 1st number is bigger than the 2nd, it'll be different than if it's smaller.

The fiddle: https://jsfiddle.net/gfsmhy37/


Solution

  • You are missing a '#' on your jQuery call:

    window.outputBefore = function(x) {
        $("#output-before").text(x); // You were missing the # here
    };
    

    Also, some other things: Change

      window.ACTIVE_NUMBER;
      window.LAST_NUMBER;
    

    To:

    var ACTIVE_NUMBER;
    var LAST_NUMBER;
    

    Also, you need to change LAST_NUMBER before you update ACTIVE_NUMBER, that way it remembers what ACTIVE_NUMBER was before its current value.

     window.checker = function() {
       LAST_NUMBER = ACTIVE_NUMBER; // Added this line
        var foundnumber = parseInt($(".tool.active").index() + 1);
        ACTIVE_NUMBER = foundnumber;
      };
    

    And then in your click function, you need to output LAST_NUMBER:

     $(".tool").click(function() {
    
        if ($(this).hasClass("active")) {
          console.log("It is already active.");
        } else {
          $(".tool").removeClass("active");
          $(this).addClass("active");
          checker();
          outputBefore(ACTIVE_NUMBER); // Add this line
          output(LAST_NUMBER); 
        }
      });
    

    And put semi-colons after all of your functions.

    Full code:

    $(document).ready(function() {
    
      //    global variables
      var ACTIVE_NUMBER;
      var LAST_NUMBER;
    
      //    global functions
      window.output = function(x) {
        $("#output").text(x);
      };
    
      window.outputBefore = function(x) {
        $("#output-before").text(x);
      };
    
      window.checker = function() {
       LAST_NUMBER = ACTIVE_NUMBER;
        var foundnumber = parseInt($(".tool.active").index() + 1);
        ACTIVE_NUMBER = foundnumber;
      };
    
      //    the starting value
      //    if(LAST_NUMBER == undefined){
      //        LAST_NUMBER = 1;
      //    }
    
      checker();
    output(ACTIVE_NUMBER);
    outputBefore(LAST_NUMBER);
    
    
    
    
    
      //    Changes applied onclick event
      $(".tool").click(function() {
    
        if ($(this).hasClass("active")) {
          console.log("It is already active.");
        } else {
          $(".tool").removeClass("active");
          $(this).addClass("active");
          checker();
          outputBefore(ACTIVE_NUMBER);
          output(LAST_NUMBER);
        }
      });
    
    
    });