SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Jun 2014
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Logical Operator Issue with Keyboard events

    I have created a few different conditions to handle different keyboard events within a simple calculator program I am working on.

    Code:
    if (keys[16] && keys[187]) {
    		pressplus();
    	}
    if (keys[187]) {
    	       pressequal();	
    	}
    I want presspluss() to occur when I press shift and the += key, and I want pressequal() to occur when I press the += key alone. But everytime I press shift and the += key both pressplus() and pressequal() occur simaltaneously.

    Is there a way to make these two events exclusive? I thought the && logical operator would do the job, but it seems inadequate.

  2. #2
    SitePoint Member
    Join Date
    Aug 2013
    Location
    San Francisco, CA
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try using something like:

    Code:
    document.onkeypress = function (event) {
        if (event.keyCode === 187 && event.shiftKey) {
            pressplus();
        }
        if (event.keyCode === 187 && !event.shiftKey) {
            pressequal();
        }
    };
    Because you're using separate logic statements remember anytime you press the +/= key both expressions will be true, so both will fire. By checking to make sure that the shift key is not being pressed in the second logic statement you should only see one or the other fire. If I saw more of your code I'd more than likely recommend a much cleaner logic system, but I went with separate statements to keep it closer to what you have already.
    Last edited by Valjas; Jun 29, 2014 at 21:24. Reason: Added more explanation

  3. #3
    SitePoint Member
    Join Date
    Jun 2014
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you very much! As of now my code is certainly not the cleanest or most efficient, but this is my first project (I am fairly new to programming and have been trying to learn html/css/js over the past couple of months in my spare time). Thanks again!

  4. #4
    SitePoint Addict bronze trophy WolfShade's Avatar
    Join Date
    Mar 2014
    Location
    St. Louis, MO, USA
    Posts
    323
    Mentioned
    9 Post(s)
    Tagged
    0 Thread(s)
    Code:
    document.onkeypress = function(event){
    (event.keyCode === 187) ?
        (event.shiftKey) ? pressplus() : pressequal() ; : ;
    };
    Untested, but looks like shorthand, to me.
    V/r,

    ^_^
    WolfShade The Spamhater


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •