Skip to content

Instantly share code, notes, and snippets.

@Peleg
Created June 3, 2016 01:04
Show Gist options
  • Save Peleg/0596781c0bf7472e9c5f079dbbb7ebab to your computer and use it in GitHub Desktop.
Save Peleg/0596781c0bf7472e9c5f079dbbb7ebab to your computer and use it in GitHub Desktop.

#jquery calculator:

  1. create html file and include the dependencies (jquery, bootstrap);

  2. create html layout on page. that includes: script, buttons (numbers, clear, operators, equals);

  3. declare variables for the numbers:

    • first number,
    • second number
    • result
  4. declare variable for the operator;

  5. attach an event handler to the numbers (ie $('.number').on('click', function...)) and inside the event handler (function):

    1. store the number pressed as a string in the first number variable
    2. when a number is clicked again, concatenate with what we have stored in the first number var.
    3. if we have an operator stored in our operator variable, then concatenate to second number var, otherwise concatenate to first number var.
  6. attach an event handler to all our operators so we can store which one was picked in our operator variable.

  7. attach an event handler to the equal button which will calculate the result and print to the screen based on the operator that's stored in the operator variable.

Note: infer what button was clicked using "this" which will have a reference to the button which was clicked

var operator;

// html: <button class="operator" value="+"> + </button>
$('.operator').on('click', function () {
	// this ===	the clicked btn
	operator = $(this).data('operator');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment