Make it work only with left mouse down - javascript

Holla ,
this is the javascript im using
var timeoutID;
function setup() {
document.getElementById("demo").addEventListener("mousedown", resetTimer);
startTimer();
}
setup();
function startTimer() {
timeoutID = window.setTimeout(goInactive, 1000);
}
function resetTimer() {
window.clearTimeout(timeoutID);
goActive();
}
function goInactive() {
document.getElementById("demo").style.opacity = 0;
document.getElementById("demo").style.transition = "1s";
}
function goActive() {
document.getElementById("demo").style.opacity = 1;
document.getElementById("demo").style.transition = "1s";
startTimer();
}
everything is working fine , except i want it to go active only by left mouse button ( now right click left click and middle click are doing the job )
So many thanks in advance
AliYous

You have to detect the left mouse button press by checking the event object (Detect left mouse button press).
evt = evt || window.event;
if ("buttons" in evt) {
return evt.buttons == 1;
}
And then if it's left mouse (1), proceed to do your job in resetTimer() function. Final code will be:
function resetTimer(e) {
evt = e || window.event;
if ("buttons" in evt) {
if (evt.buttons == 1) {
window.clearTimeout(timeoutID);
goActive();
}
}
}

You can use the mouseup event on the element you want to use as the trigger.
You haven't said what you click so I used document in the example below.
The below example is taken pretty much straight from the Mouse Event Button Documentation
document.addEventListener('mouseup', function(e) {
var e = e || window.event;
var btnCode;
btnCode = e.button;
switch (btnCode) {
case 0:
console.log('Left button clicked.');
break;
case 1:
console.log('Middle button clicked.');
break;
case 2:
console.log('Right button clicked.');
break;
default:
console.log('Unexpected code: ' + btnCode);
}
})
The short version more applicable to your scenario could look like the blow:
var resetTimer = function() {
console.log('resetTimer called');
};
document.addEventListener('mouseup', function(e) {
var e = e || window.event;
var btnCode;
btnCode = e.button;
if (btnCode === 0) {
resetTimer();
}
})

Related

Javascript - Increasing value by keypress, only once

im trying to get the value of a variable that i have to increase by 5 each time that the up key is pressed.
Currently i have the variable increasing upon keypress etc but the main problem i have is that from one keypress, the value will continue rise. For example, value would start at 5, upon one keypress would continue to rise by 5 each time and would stop just after 600. Whereas i want it to start at 5 then upon each keypress go to 10,15,20....
Here's the code i have, i'd be grateful for the help on where im going wrong etc
var projectoryHeight = 5;
function setHeight()
{
projectoryHeight = projectoryHeight + 5;
};
if (keyCode == 38)
{
setHeight();
console.log(projectoryHeight);
};
The code that relates to keycode for the up key being placed, is inside a rendering function, for use with requestAnimationFrame(). I feel like this may be what is causing the issue of it continuing to count however I have tried moving it outside of this function and nothing happens.
Javascript being used alongside THREE.js & Physi.js
More code to help with problem:
var render = function() {
requestAnimationFrame(render);
scene.simulate();
let keyFlag = false;
// Update the title page shape rotations
sphere.rotation.y += 0.06;
sphere.rotation.x += 0.10;
sphere.rotation.z += 0.06;
document.addEventListener("keydown", (e) => {
if(e.code == 'KeyW'){
$(title).hide();
$(keyTitle).hide();
scene.remove(sphere);
sphere.geometry.dispose();
sphere.material.dispose();
//add all the game functions here
scene.add(cube);
scene.add(firingBall);
scene.add(struct1);
scene.add(struct2);
scene.add(struct3);
scene.add(struct4);
scene.add(struct5);
scene.add(struct6);
scene.simulate();
}
});
document.addEventListener("keydown", (e) => {
if(e.code == 'Space'){
firingBall.setLinearVelocity(new THREE.Vector3(speedOfBall, projectoryHeight, 0));
}
});
document.addEventListener("keydown", (e) => {
if(e.code == 'ArrowUp'){
if (!keyFlag) {
keyFlag = true;
projectoryHeight = projectoryHeight + 5;
console.log(projectoryHeight);
}
}
});
document.addEventListener("keydown", (e) => {
if(e.code == 'ArrowDown'){
if (!keyFlag) {
keyFlag = true;
projectoryHeight = projectoryHeight - 5;
console.log(projectoryHeight);
}
}
});
document.addEventListener("keyup", (e) => {
if(e.code == 'ArrowUp'){
if (keyFlag){
console.log("stopped");
keyFlag = false;
}
}
});
document.addEventListener("keyup", (e) => {
if(e.code == 'ArrowDown'){
if (keyFlag){
console.log("stopped");
keyFlag = false;
}
}
});
renderer.autoClear = false;
renderer.clear();
renderer.render(backgroundScene, backgroundCamera);
renderer.render(scene, camera);
};
This is the function where keypresses etc are used, inside the render function. Also starts the animation frames and game physics.
This function is then called directly after it is declared
Thanks
You need to set a flag that tells you whether or not a key is being held down. To do this in simple form, you can use the keydown event in conjunction with the keyup event. In the following code the key can be held down but it only performs an action once based on the flag.
i.addEventListener("keydown", (e) => {
if (!keyflag) console.log(e.key);
keyflag = true;
});
i.addEventListener("keyup", (e) => {
if (keyflag) console.log("released!");
keyflag = false;
});
let i = document.querySelector("input"),
keyflag = false;
i.addEventListener("keydown", (e) => {
if (!keyflag) console.log(e.key);
else e.preventDefault();
keyflag = true;
});
i.addEventListener("keyup", (e) => {
if (keyflag) console.log("released!");
else e.preventDefault();
keyflag = false;
});
<input>
Note inside the snippet I use e.preventDefault() to stop letters appearing in the input box. My intention was only that this would make it easier to see.

How to simulate multiple keypress event at the same time

I found this way, but with it I can only set one keycode in .which, I want to simulate the keys ALT+space+x at the same time.
For ALT I can use .altKey = true;
$(".btn").click(function() {
var e = jQuery.Event("keypress");
e.which = 88; // x code value
e.altKey = true; // Alt key pressed
$("input").trigger(e);
});
How do I add space keycode?
I apologize for my previous answer. I thought about how to handle. Now I modify code to handle and trigger:
You can implement it with two events: keyDown and keyUp like this:
var x,
alt,
space;
document.addEventListener('keydown', function (e) {
e = window.event ? event : e;
switch (e.keyCode) {
case 88:
x = true;
break;
case 18:
alt = true;
break;
case 32:
space = true;
break;
}
});
document.addEventListener('keyup', function (e) {
if (x && alt && space) {
alert("alt + space + x Pressed!");
}
x = alt = space = false;
});
function triggerEvent(eventName, keyCode) {
var event; // The custom event that will be created
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.keyCode = keyCode || null;
if (document.createEvent) {
document.dispatchEvent(event);
} else {
document.fireEvent('on' + event.eventType, event);
}
}
triggerEvent('keydown', 88);
triggerEvent('keydown', 18);
triggerEvent('keydown', 32);
triggerEvent('keyup');
https://jsfiddle.net/m83omwq5/1/

Javascript Play/Pause button Keyboard event

I'm still working on a music player, mouse controls have been assigned, but I'm having little trouble with keyboard events on the PLAY/PAUSE button.
So far, I got the user to be able to "click" the PLAY button by pressing SPACEBAR. What happens is that the PLAY button is being hidden and replaced by the PAUSE button.
Which I want now is getting the user to be able to press the SPACEBAR again so it "clicks" PAUSE, and therefore shows PLAY again.
Here is what I have :
html
<div>
</div>
script
<script>
/* mouse */
$('#play').on('click', function(event) {
console.log('play click clicked');
//currentPlayingTrack.play();
$('#pause').show();
$('#play').hide();
$('#pause').on('click', function(event) {
//currentPlayingTrack.pause();
$('#pause').hide();
$('#play').show();
});
/* keyboard */
var play = document.getElementById("play");
var pause = document.getElementById("pause");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
else if(e.keyCode == 32) {
pause.click();
}
};
</script>
What am I missing ?
the mistake is here:
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
} else if(e.keyCode == 32) {
pause.click();
}
};
the second condition cannot be executed because everytime the keyCode is 32 it's goes only in the first conditions.
You can declare a variable "isPlaying" that indicate you if the player is playing.
var isPlaying = false;
document.onkeydown = function (e) {
if (e.keyCode == 32) {
if (isPlaying) {
pause.click();
} else {
play.click();
}
isPlaying = !isPlaying; // if true equal false, if false equal true
}
};
the first mistake is that you arent closing all brackets,the second is this part of code:
if (e.keyCode == 32) {
play.click();
}
else if(e.keyCode == 32) {
pause.click();
}
i suggest to use a variable for check if the button play is being pressed or not:
var ispaused = true;
var play = document.getElementById("play");
var pause = document.getElementById("pause");
$('#play').on('click', function(event) {
ispaused = false;
console.log('play click clicked');
//currentPlayingTrack.play();
$('#pause').show();
$('#play').hide();
/* keyboard */
});
$('#pause').on('click', function(event) {
ispaused = true;
//currentPlayingTrack.pause();
$('#pause').hide();
$('#play').show();
});
document.onkeydown = function (e) {
if (e.keyCode == 32) {
if(ispaused == true ){
play.click();
}else{
pause.click();
}
}
};
fiddle
It works. you double check space keyCode when you space anytime and the first condition would be true every single time.
Second, you need to use $bla instead for $("#blablabla") .It runs almost 600 line Code with find object you select everytime.So don't be let duplicate work.
Final,$() is lik $(doucument).ready().It's all done when rendered it's done and DOM it's OK.THAT IS!
** code **
$(function () {
let $play = $("#play");
let $pause = $("#pause");
$play.on('click', function (event) {
console.log('play click clicked');
//currentPlayingTrack.play();
$pause.show();
$play.hide();
});
$pause.on('click', function (event) {
//currentPlayingTrack.pause();
$pause.hide();
$play.show();
});
/* keyboard */
document.onkeydown = function (e) {
if (e.keyCode == 32) {
toggle = !toggle;
$play.trigger("click");
}
else if (e.keyCode == 32) {
toggle = !toggle;
$pause.trigger("click");
}
};
});
Seems like you're missing a bit more knowledge of js which will come with time :) Here's a codepen on how I'd accomplish this.
http://codepen.io/smplejohn/pen/zNVbRb
Play
Pause
$('.playpause').click(function(){
$('.playpause').toggle();
return false;
});
document.onkeydown = function (e) {
if (e.keyCode == 32){
$('.playpause').toggle();
}
};

Key pressed and click in the same time

how can I merge keypress and on click? I mean when a user press enter and click somewhere in the same time I need to invoke a function.
$(document).keypress(function(e) {
var code = e.keyCode || e.which;
if(code == 13) {
alert('keypress');
}
});
$(document).on( "click", function() {
alert('click');
});
I have this code but I am not able to merge it (usually I don't work with jQuery/javascript).
Something like this may do the trick
var pressingEnter = false;
$(document).on({
keydown: function(e) {
if(e.which == 13) {
// enter is being pressed, set true to flag variable
pressingEnter = true;
}
},
keyup: function(e) {
if(e.which == 13) {
// enter is no longer pressed, set false to flag variable
pressingEnter = false;
}
},
click: function() {
if (pressingEnter) {
console.log('click and enter pressed');
}
}
});
BTW: there is no need to do var code = e.keyCode || e.which; since jQuery resolves that for you. You can use e.which on any browser.
EDIT
This version should allow any order of key pressed / mouse click. I'm assuming only left click is captured. Logic to handle enter + mouse click is placed on keydown and mousedown (it could be moved to keyup and mouseup if makes more sense)
Changed alert by console.log since the first prevents mouseup event to be triggered. Nowdays we have hundred of better ways to show a message to user than built-in alert pop ups so I'll assume making it work for it is not a requirement.
var pressingEnter = false;
var clickingMouseButton = false;
$(document).on({
keydown: function(e) {
if(e.which == 13) {
pressingEnter = true;
}
if (clickAndEnterPressing()) {
console.log('click and enter pressed');
}
},
keyup: function(e) {
if(e.which == 13) {
pressingEnter = false;
}
},
mousedown: function(e) {
if (e.which == 1) {
clickingMouseButton = true;
}
if (clickAndEnterPressing()) {
console.log('click and enter pressed');
}
},
mouseup: function(e) {
if (e.which == 1) {
clickingMouseButton = false;
}
}
});
function clickAndEnterPressing() {
return pressingEnter && clickingMouseButton;
}
Here's an example that will work if enter is pushed first or if the mouse is clicked first or if they are both pressed within a certain threshold of time apart (I set it to 100 ms, but this can be easily adjusted):
var enterDown = false;
var mouseDown = false;
var lastEnter = false;
var lastMouseUp = false;
var triggerOnNextUp = false;
$(document).on({
keydown: function(e) {
enterDown = true;
},
keyup: function(e) {
if(e.which == 13) {
lastEnter = (new Date()).getTime();
enterDown = false;
detectEnterAndClick();
if (mouseDown) {
triggerOnNextUp = true;
}
}
},
mousedown: function() {
mouseDown = true;
},
mouseup: function() {
lastMouseUp = (new Date()).getTime();
mouseDown = false;
detectEnterAndClick();
if (enterDown) {
triggerOnNextUp = true;
}
}
});
function detectEnterAndClick() {
if (Math.abs(lastEnter - lastMouseUp) < 100 || triggerOnNextUp) {
// Reset variables to prevent from firing twice
triggerOnNextUp = false;
enterDown = false;
mouseDown = false;
lastEnter = false;
lastMouseUp = false;
$("body").append("Clicked and pushed enter<br>");
}
}
See it on JSFiddle
There is no way to 'merge' events. However you could for example debounce your handler. For example (using lodash):
var handler = _.debounce(function(event) { alert(event.type); }, 100);
$(document)
.on('click', handler)
.on('keypress', handler);
you can use the event.type to determine what triggered the event
Demo
$(function(){
$(document).on("click", ClickAndKeyPress);
$(document).on("keypress", ClickAndKeyPress);
});
function ClickAndKeyPress(event){
$("div").text(event.type);
}

javascript keypress to control animation

Space Invader game: I want to control the 'base gun' (move it left and right and fire missiles at the invaders. So I need a keypress or (keydown?) event to change a variable (x coordinate) and a key press event to fire a missile.
Can anyone show me how the keypress event is detected and the variable is changed?
document.onkeydown = function(e) {
var key = e.keyCode;
if (key===37) {//left arrow pressed
} else if (key===39) {//right arrow pressed
}
}
Like this?
document.onkeydown = checkKey;
var xCoord = 100;
function checkKey(e) {
e = e || window.event;
switch (e.keyCode) {
case 37 : // left
xCoord -= 5;
break;
case 39 : // right
xCoord += 5;
break;
}
}
Exciting fiddle: http://jsfiddle.net/u5eJp/
Couple things I would like to add to the other answers:
1) Use constants to make it easier on yourself
2) There is no way to check if a key is currently pressed in javascript, so you should keep track of what is currently pressed as well
var pressed = {
up: false,
down: false,
left: false,
right: false
};
var LEFT_ARROW = 37;
var UP_ARROW = 38;
var RIGHT_ARROW = 39;
var DOWN_ARROW = 40;
document.onkeydown = function (e) {
e = e || window.event;
switch (e.keyCode) {
case LEFT_ARROW:
pressed.left = true;
break;
case UP_ARROW:
pressed.up = true;
break;
case RIGHT_ARROW:
pressed.right = true;
break;
case DOWN_ARROW:
pressed.down = true;
break;
default:
break;
}
}
//update position separately
function updatePos() {
if (pressed.up) { //change y up }
if (pressed.down) { //change y down }
if (pressed.left) { //change x left }
if (pressed.right) { //change x right }
}
Hope this helps, and good luck!

Categories