stop play video when I'm focus textarea - javascript

When I keyup spacebar, paly video.
But If I focus on the 'textarea' for writing play video too.
i wanna stop video if i focus on the textarea. help me!
window.onkeypress = function(e) {
if (e.srcElement.className.indexOf('dragClass') > -1) {
if (e.keyCode === 1300) {
divWidth = document.getElementById('controlBar').clientWidth;
if (divWidth < canvas.width)
scale = divWidth / canvas.width;
else
scale = 1;
curSize += 0;
ctx.font = curSize + 'px Arial';
ctx.fillStyle = curColor;
ctx.fillText(textBox.value, mouseX / scale, mouseY / scale);
videoDiv.removeChild(textBox);
}
} else if (e.srcElement.id == 'textArea') {;
} else {
if (e.keyCode === 32) {
$('.play-pause-btn-' + modalId).blur();
if (vid.paused) {
vid.play();
playbtn.style.background = "url(/assets/images/common/btn_pause_black.png) 50% 50% no-repeat";
loop();
} else {
vid.pause();
playbtn.style.background = "url(/assets/images/common/btn_play_black.png) 50% 50% no-repeat";
}
}
if (e.keyCode === 44) {
previousframeStep();
}
if (e.keyCode === 46) {
nextframeStep();
}
}
Here my code.

Instead of "e.srcElement.id" use "e.target.id". Also it would be better if the textArea object had a event listener that triggered to do what you want rather than the window object.
If you are wanting to check via the "id" method you should also have a safety check in there as well, because not all objects have a id property and that will throw a error!
if (e.target.id && e.target.id === "textarea")\\then do whatever

Related

Why and (&) in if statement is not working? [duplicate]

This question already has answers here:
How to detect if multiple keys are pressed at once using JavaScript?
(19 answers)
Closed 5 years ago.
So i am making a html5 game where i was working in movement. Player can move with w, a, s ,d in key. That is working well but i wanted to add a power ..like if player press a + space-bar or d + space-bar an ability will trigger.
i used and operator and it should have worked in my theory but it's not working.
I am new in html5 and any help will be appreciated. thanks in advance.
Here is my code... Just copy paste on html note.
<canvas id="canvas" width="800" height="500" style="border:1px solid #000000;"></canvas>
<script>
var c = document.getElementById("canvas").getContext("2d");
var WIDTH = 800;
var HEIGHT = 500;
var player = {
x: Math.random() * WIDTH,
y: Math.random() * HEIGHT,
width: 30,
height: 30,
color: 'black',
pressingDown: false,
pressingUp: false,
pressingLeft: false,
pressingRight: false,
pressinpowerRight: false,
pressinpowerLeft: false,
};
drawEntity = function(e) {
c.fillStyle = e.color;
c.fillRect(e.x - e.width / 2, e.y - e.height / 2, e.width, e.height);
}
document.onkeydown = function(event) {
if (event.keyCode === 68) //d
player.pressingRight = true;
else if (event.keyCode === 83) //s
player.pressingDown = true;
else if (event.keyCode === 65) //a
player.pressingLeft = true;
else if (event.keyCode === 87) // w
player.pressingUp = true;
else if (event.keyCode === 68 && event.keyCode === 32) // this statement is not working
player.pressinpowerRight = true;
else if (event.keyCode === 65 && event.keyCode === 32) // this statement is not working
player.pressinpowerLeft = true;
}
document.onkeyup = function(event) {
if (event.keyCode === 68) //d
player.pressingRight = false;
else if (event.keyCode === 83) //s
player.pressingDown = false;
else if (event.keyCode === 65) //a
player.pressingLeft = false;
else if (event.keyCode === 87) // w
player.pressingUp = false;
else if (event.keyCode === 68 && event.keyCode === 32) // not working
player.pressinpowerRight = false;
else if (event.keyCode === 65 && event.keyCode === 32) // not working
player.pressinpowerLeft = false;
}
updatePlayerPosition = function() {
if (player.pressingRight)
player.x += 5;
if (player.pressingLeft)
player.x -= 5;
if (player.pressingDown)
player.y += 5;
if (player.pressingUp)
player.y -= 5;
if (player.pressingpowerRight)
player.x += 50;
if (player.pressingpowerLeft)
player.x -= 50;
}
update = function() {
c.clearRect(0, 0, WIDTH, HEIGHT);
updatePlayerPosition();
drawEntity(player);
}
setInterval(update, 40);
</script>
Try creating a previousButtonKey global variable and always record the last key, then check the previousButtonKey with another key to combine two keys on your condition.
Ex. First key is to be pressed is 'Shift', store it to a variable, then once another key event happens, check the previous and the new key. If it is valid, then do the action that you want.

How to make a border?

I have element
<div id="square"></div>
He has a property to move on document
var square = document.getElementById("square");
document.body.onkeydown = function(e) {
if (e.keyCode == 37) {left()}
if (e.keyCode == 38) {up()}
if (e.keyCode == 39) {right()}
if (e.keyCode == 40) {down()}
}
How I make a function, which not allowed movement, if square element is closest to document border?
JSFiddle: https://jsfiddle.net/zutxyLsq/
You need to check if left is outside of boundaries like this:
function left() {
console.log('Left');
var left = parseInt(square.style.left || getComputedStyle(square)['left'], 10);
if (left >= 50) {
square.style.left = (left - 50) + 'px';
}
}
function right() {
console.log('Right');
var left = parseInt(square.style.left || getComputedStyle(square)['left'], 10);
if (left+50+square.offsetWidth < window.innerWidth) {
square.style.left = (left + 50) + 'px';
}
}
https://jsfiddle.net/zutxyLsq/3/
and the same for up and down.

Moving diagonally in 2d canvas JavaScript game

I've scoured the web for this answer. If it is buried in a StackOverflow answer somewhere I apologize.
I am working on a 2d canvas JavaScript game.
I am handling arrow key input with onkeydown and onkeyup events.
I store this input in an object called Keys.
var Keys = {
up: false,
down: false,
left: false,
right: false
};
This is what my event handlers look like:
window.onkeydown = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = true;
else if(kc === 38) Keys.up = true;
else if(kc === 39) Keys.right = true;
else if(kc === 40) Keys.down = true;
move();
};
window.onkeyup = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = false;
else if(kc === 38) Keys.up = false;
else if(kc === 39) Keys.right = false;
else if(kc === 40) Keys.down = false;
};
Then each time the keydown event occurs, I call my move() function:
var move = function(){
if(Keys.up){
hero.y -= 10;
}
else if(Keys.down){
hero.y += 10;
}
if(Keys.left){
hero.x -= 10;
}
else if(Keys.right){
hero.x += 10;
}
main();
}
The move() function calls my main() function which just draws the map again.
I'm trying to avoid looping the game, and instead update the map each time the player moves.
So my problem arises when I try to move diagonally. I am able to do it, however once I release the second key pressed, my character stops.
For example:
Right key pressed and then up key pressed, character moves northeast.
Up key released, player stops.
However, if I release the right key, the character continues moving up.
Another glitch is when I hold both left and right, the character will move left,
but I want it to stop moving.
Quickly sketched an example, jsfiddle: http://jsfiddle.net/ofnp4vj4/
HTML: <div id="log"></div>
JS:
var Keys = {
up: false,
down: false,
left: false,
right: false
};
var hero = {
x: 0,
y: 0
};
var log = document.getElementById("log");
window.onkeydown = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = true;
if(kc === 38) Keys.up = true;
if(kc === 39) Keys.right = true;
if(kc === 40) Keys.down = true;
};
window.onkeyup = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = false;
if(kc === 38) Keys.up = false;
if(kc === 39) Keys.right = false;
if(kc === 40) Keys.down = false;
};
function main() {
/* body */
move();
log.innerHTML = "x: "+hero.x+", y: "+hero.y;
};
function move(){
if(Keys.up){
hero.y -= 10;
}
if(Keys.down){
hero.y += 10;
}
if(Keys.left) {
hero.x -= 10;
}
if(Keys.right){
hero.x += 10;
}
}
setInterval(main, 100);
You mention that you want the player to stop moving when you press the left and right keys simultaneously. It appears you should be able to easily do this by replacing the else if statements in move with if statements, resulting in a move function similar to:
var move = function(){
if(Keys.up){
hero.y -= 10;
}
if(Keys.down){
hero.y += 10;
}
if(Keys.left){
hero.x -= 10;
}
if(Keys.right){
hero.x += 10;
}
main();
}

Mouseclick event inside mouseclick event works with IE and other browsers, not with firefox

Please see below code... Aims of the code is to display a floating menu on right clicking the screen and the menu should hide on left clicking the screen. The below works perfectly with IE and Chrome, but fails in firefox. I tried debugging with firebug, no positives at all.
$(document).ready(function () {
document.onmousedown = onMouseClick;
}
function onMouseDown(ev) {
document.oncontextmenu = onClickRightMouseButton; //to hide default menu on right click
if (ev.which == 1) {
console.log('1');
}
if (ev.which == 2) {
console.log('2');
}
if (ev.which == 3) {
var xPos = ev.clientX;
var yPos = ev.clientY;
document.onmousedown = onMouseClick;
showFloatingMenu(xPos, yPos);
}
function onMouseClick(e) {
if (e.which == 1) {
if (!(e.clientX >= xPos && e.clientX <= (xPos + 200) && e.clientY >= yPos && e.clientY <= (yPos + 50))) { //50x200 is the floating menu diamension
hideFloatingMenu();
}
}
}
}
}

ipad/iphone carousel not working as expected with touchmove

I have a carousel that is working just fine for all browsers and all devices except for ipad/iphone. When I swipe the carousel, it will use jqueries easing and bounce several times before stopping. The only way to make it behave, as it does in all other browsers, is to have an alert message pop up after swiping, then it works perfectly.
[code]
$("#CarouselWrap").bind("touchmove", function(event){
if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
whichWayMovingX[1] = event.originalEvent.touches[0].pageX;
whichWayMovingY[1] = event.originalEvent.touches[0].pageY;
}else{
whichWayMovingX[1] = event.originalEvent.changedTouches[0].pageX;
whichWayMovingY[1] = event.originalEvent.changedTouches[0].pageY;
}
if(whichWayMovingX[0] > whichWayMovingX[1]){
if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)){
alert("left");
moveLeft();
}else{
moveLeft();
}
}else{
if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)){
alert("right");
moveRight();
}else{
moveRight();
}
}
});
[/code]
The moveLeft and moveRight functions are used with the arrows on the left and right of the carousel, so I know that these work, but only for onclick events.
[code]
switch(amountToMove) {
case -1011:
$("#CarouselFeed").animate({marginLeft: amountToMove},{duration: 'slow', easing: 'easeOutBack', wipe:'true'});
[/code]
Why would this code work so well for onclick, but not for touchmove?
I have tried to combine the binds of touchstart, touchend and touchmove - nada
I have tried to use touchmove mousemove - diddlesquat
I have tried to use a setTimeout thinking that I had to wait for the last event - nothing
Please help, this is driving me nuts.
Found the solution via some code for addressing the default behavior of a swipe.
First, set up the listeners:
if(document.getElementById("CarouselFeed")){
$("#CarouselFeed").bind("touchstart", function(event){
touchStart(event,"CarouselFeed")
});
$("#CarouselFeed").bind("touchend", function(event){
touchEnd(event);
});
$("#CarouselFeed").bind("touchmove", function(event){
touchMove(event);
});
}
I found the following code on a web site, that thanked two other web sites for their code and just as that web site changed the code a little to suit their needs, I have done the same:
// TOUCH-EVENTS SINGLE-FINGER SWIPE-SENSING JAVASCRIPT
// Courtesy of PADILICIOUS.COM and MACOSXAUTOMATION.COM
// redefined a few things to make this applicable to our needs
// this script can be used with one or more page elements to perform actions based on them being swiped with a single finger
var triggerElementID = null; // this variable is used to identity the triggering element
var fingerCount = 0;
var startX = 0;
var startY = 0;
var curX = 0;
var curY = 0;
var deltaX = 0;
var deltaY = 0;
var horzDiff = 0;
var vertDiff = 0;
var minLength = 72; // the shortest distance the user may swipe
var swipeLength = 0;
var swipeAngle = null;
var swipeDirection = null;
// The 4 Touch Event Handlers
// NOTE: the touchStart handler should also receive the ID of the triggering element
// make sure its ID is passed in the event call placed in the element declaration, like:
//
var touchStart = function(event,passedName){
// disable the standard ability to select the touched object
// event.preventDefault();
// get the total number of fingers touching the screen
fingerCount = event.originalEvent.touches.length;
// since we're looking for a swipe (single finger) and not a gesture (multiple fingers),
// check that only one finger was used
if(fingerCount == 1){
// get the coordinates of the touch
startX = event.originalEvent.touches[0].pageX;
startY = event.originalEvent.touches[0].pageY;
// store the triggering element ID
triggerElementID = passedName;
}else{
// more than one finger touched so cancel
touchCancel(event);
}
}
var touchMove = function(event){
event.preventDefault();
if ( fingerCount == 1 ){
curX = event.originalEvent.touches[0].pageX;
curY = event.originalEvent.touches[0].pageY;
}else{
touchCancel(event);
}
}
var touchEnd = function(event){
// event.preventDefault();
// check to see if more than one finger was used and that there is an ending coordinate
if (fingerCount == 1 && curX != 0){
// use the Distance Formula to determine the length of the swipe
swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2)));
// if the user swiped more than the minimum length, perform the appropriate action
if(swipeLength >= minLength){
caluculateAngle();
determineSwipeDirection();
processingRoutine();
touchCancel(event); // reset the variables
}else{
touchCancel(event);
}
}else{
touchCancel(event);
}
}
var touchCancel = function(event){
// reset the variables back to default values
fingerCount = 0;
startX = 0;
startY = 0;
curX = 0;
curY = 0;
deltaX = 0;
deltaY = 0;
horzDiff = 0;
vertDiff = 0;
swipeLength = 0;
swipeAngle = null;
swipeDirection = null;
triggerElementID = null;
}
var caluculateAngle = function(){
var X = startX-curX;
deltaX = X;
var Y = curY-startY;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians (Cartesian system)
swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if (swipeAngle < 0) {swipeAngle = 360 - Math.abs(swipeAngle);}
}
var determineSwipeDirection = function(){
if( (swipeAngle <= 45) && (swipeAngle >= 0) ){
swipeDirection = 'left';
}else if( (swipeAngle <= 360) && (swipeAngle >= 315) ){
swipeDirection = 'left';
}else if( (swipeAngle >= 135) && (swipeAngle <= 225) ){
swipeDirection = 'right';
}else if( (swipeAngle > 45) && (swipeAngle < 135) ){
swipeDirection = 'down';
}else{
swipeDirection = 'up';
}
}
var processingRoutine = function(){
var swipedElement = document.getElementById(triggerElementID);
if( swipeDirection == 'left' ){
moveLeft();
}else if( swipeDirection == 'right' ){
moveRight();
}else if( (swipeDirection == 'up') || (swipeDirection == 'left') ){
moveLeft();
}else if( (swipeDirection == 'up') || (swipeDirection == 'right') ){
moveRight();
}else if( (swipeDirection == 'down') || (swipeDirection == 'left') ){
moveLeft();
}else if( (swipeDirection == 'down') || (swipeDirection == 'right') ){
moveRight();
}
}
One note, I have this swipe working on a carousel that has banners. In order for the links for the banners to work, you have to comment out the event.preventDefault() within the touchStart and touchEnd functions.
And that is all it takes

Categories