Quit Application in Java Script? - javascript

i need to quit application as soon as stop button pressed from HTML.The start and stop button working fine but the problem with stop button is that it pause the game not quit the application. i wrote this code in else block window.setTimeout(animloop, 1000); it will pause the game but not quit the game or if i use windows.close() it will close browser immediately .
my code:
var gameStarted = false;
// Infinte loop for game play
(function animloop() {
if (gameStarted) {
requestAnimFrame(animloop);
render();
} else {
window.setTimeout(animloop, 1000); // check the state per second
}
})(); // ends (function animloop() )
}); // ends $(doc).ready
HTML code:
<html>
<head>
<link rel="icon" href="./arrows/clubbackground.jpg" type="image/gif" sizes="16x16">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="jsRev.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>DDR-Project 1</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="BackgroundScene">
<div id="DanceScoreboard">
<div id="GameStopped"><button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">Begin Game</button>
<br><br><br>
<div class="Status">Click Begin Game to start</div>
</div>
<div id="GameRunning"><button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">Stop Game</button>
<div id="Status" class="Status"></div>
</div>
<div id="dancePoints" class="Points">Points Earned:
<div class="OutputText" id="CorrectCount">0</div>
</div>
</div>
<div class="stage"></div>
<!-- ENDS .STAGE -->
<div id="controls">
<img id="left" src="./arrows/staticLeft.png">
<img id="up" src="./arrows/staticUp.png">
<img id="down" src="./arrows/staticDown.png">
<img id="right" src="./arrows/staticRight.png">
</div>
<!-- ENDS #CONTROLS -->
</body>
</html>
java script code:
var notes = [];
var gameStarted = false;
var Score = 0;
// ==== CLASS FOR ARROWS ==== //
// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the
// 4. Explode when arrow gets to the bottom
// Class Arrow
function Arrow(direction) {
// CSS spacings for the arrows //
var xPos = null;
switch (direction) {
case "left":
xPos = "350px";
break;
case "up":
xPos = "420px";
break;
case "down":
xPos = "490px";
break;
case "right":
xPos = "560px";
break;
}
this.direction = direction;
this.image = $("<img src='./arrows/" + direction + ".gif'/>");
this.image.css({
position: "absolute",
top: "0px",
left: xPos
});
$('.stage').append(this.image);
} // ends CLASS Arrow
// To enable animating the arrows
Arrow.prototype.step = function() {
// Controls the speed of the arrows
this.image.css("top", "+=4px");
};
// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {
// removes the image of the DOM
this.image.remove();
// Removes the note/arrow from memory/array
notes.splice(0, 1);
};
// Explodes arrow when hit
Arrow.prototype.explode = function() {
this.image.remove();
};
// For random arrows
var randNum = 0;
// Frame increasing
var frame = 0;
// Determines the speed of notes
var arrowSpawnRate = 40;
// Random generator for arrows
function randomGen() {
// Randomizes between 1 and 4
randNum = Math.floor(Math.random() * 4) + 1;
if (randNum === 1) {
notes.push(new Arrow("left"));
}
if (randNum === 2) {
notes.push(new Arrow("right"));
}
if (randNum === 3) {
notes.push(new Arrow("up"));
}
if (randNum === 4) {
notes.push(new Arrow("down"));
}
} // ends randomGen()
// Render function //
function render() {
if (frame++ % arrowSpawnRate === 0) {
randomGen();
}
// Animate arrows showering down //
for (var i = notes.length - 1; i >= 0; i--) {
notes[i].step();
// Check for cleanup
if (notes[i].image.position().top > 615) {
notes[i].destroy();
}
}
} // ends render()
// jQuery to animate arrows //
$(document).ready(function() {
// shim layer with setTimeout fallback
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 40 / 75);
};
})();
/* place the rAF *before* the render()
to assure as close to 60fps with the
setTimeout fallback. */
// Infinte loop for game play
(function animloop() {
if (gameStarted) {
requestAnimFrame(animloop);
render();
} else {
window.setTimeout(animloop, 1000); // check the state per second
}
})(); // ends (function animloop() )
}); // ends $(doc).ready
// Listening for when the key is pressed
$(document).keydown(function(event) {
for (var i = 0; i < notes.length; i++) {
if (event.keyCode == 37 && notes[i].direction == "left") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("LEFT! " + notes[i].explode());
Score++;
score();
}
}
if (event.keyCode == 38 && notes[i].direction == "up") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("UP! " + notes[i].explode());
Score++;
score();
}
}
if (event.keyCode == 40 && notes[i].direction == "down") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("DOWN! " + notes[i].explode());
Score++;
score();
}
}
if (event.keyCode == 39 && notes[i].direction == "right") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("RIGHT! " + notes[i].explode());
Score++;
score();
}
}
} // ends loop
}); // ends $(doc).keyup
function score() {
document.querySelector(".Points").textContent = Score;
}

What does "quit the application" mean?
You can close the browser window, or redirect the user to another route.
But the exact semantics of "quit the application" for your game in the browser need to be defined.
If you mean "Close the web browser", then you need to have your game open in a new window from the game code when it starts, so that it can close the window when it finishes.
So you have a launcher page, and that opens the game in a new window. You can then communicate between the windows, and close the child window later.
See here for an example of opening a child window. And here for closing it. And here for communicating between them.

Related

How to increase counter when the correct image is clicked

I have written in HTML and Javascript a webpage that cycles through an image of a lion and a frog. I have set 2 buttons to start and stop the images from cycling every 500ms. My problem is I am unsure how to go around creating a score function that counts the number of times a specific image is clicked. For example, if the frog image is clicked I want the score to +1 and if the lion image is clicked I want the score to -1.
Here is my code.
<html>
<head>
<title>Question 2</title>
<script>
var images = ["frog.jpg", "lion.jpg"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
function start(){
imgInterval = setInterval(displayImage, 500); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop(){
clearInterval(imgInterval);
}
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
if (imgi.onclick == 0) {
score + 1;
}
}
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br/> <br/>
<span>
<img id="image" onclick=scoreNumb() width="250px" />
</span>
<br/>
<span id="score">0</span>
</body>
</html>
replace your function scoreNumb with mine
<script>
...
var score = document.getElementById('score');
var valueScore = 0; /*created this*/
...
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
/*if (imgi.onclick == 0) {
score + 1;
}*/
/*0 = frog AND 1 = lion*/
if (imgi == 0){/*+1*/
valueScore++;
}else {
valueScore--;
}
console.log("click", valueScore);
document.getElementById('score').textContent = valueScore;
}
You are nearly there. You just need to check which image was clicked by checking the img src
If the image src is lion then you can increase the totalScore count variable update the count as well using textContent method.
function scoreNumb(e) {
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore++
} else {
totalScore--
}
score.textContent = totalScore
}
Working Demo:
var images = ["https://via.placeholder.com/150", "https://via.placeholder.com/200"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
var totalScore = 0
function start() {
imgInterval = setInterval(displayImage, 1000); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop() {
clearInterval(imgInterval);
}
function scoreNumb(e) { //This is where i think i am having issues and am unsure what to do.
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore++
} else {
totalScore--
}
score.textContent = totalScore
}
<html>
<head>
<title>Question 2</title>
<script>
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br /> <br />
<span>
<img id="image" onclick=scoreNumb(this) width="250px" />
</span>
<br />
<span id="score">0</span>
</body>
</html>
Change this variable declaration from:
let score = document.getElementById('score');
to this:
let score = 0;
then in the function named scoreNumb() change the following :
if (imgi.onclick == 0) {
score + 1;
}
to this :
if (imgi === 0) {
score += 1;
}
else{
score -= 1;
}
// Here you can update your html code with getElementById.
console.log(score)

Javascript - setInterval() still running after clearInterval() called

I'm making a game with Javascript. I have functions for moving left, right, gravity and down. The gravity function makes the player's location go to the bottom of the screen once it goes off the platform (div). When the gravity() function is called when you are moving right (OnButtonDownr()) it stops the move up from working. What I mean is that when I go right and off the platform and then try to go up it doesn't work but I can go up before I go off the platform. When I try to go up (and it doesn't work) it has a weird effect which looks like its position is being set to 0 but moving up at the same time. My code:
HTML (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<div id='level' class='level'>
<div class='start_platform' id='plat1'></div>
<div class='platform' style='
'></div>
</div>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveup' onmousedown="OnButtonDownu (this)" onmouseup="OnButtonUpu (this)">^</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
<script type='text/javascript' src='scripts/move.js'></script>
<script type='text/javascript' src='scripts/gravity.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</html>
JS (move.js):
//move left
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
gravityCheck();
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
//move right
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
gravityCheck();
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
//move up
var elem = document.getElementById("player");
function OnButtonDownu () {
var posu = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.idu = setInterval(frameu, 5);
elem.style.bottom = 0;
function frameu() {
gravity = false;
posu++;
elem.style.bottom = posu + 'px';
}}
function OnButtonUpu (button) {
clearInterval(idu);
}
JS (gravity.js):
var gravity = true;
function gravityCheck() {
var player = parseInt(document.getElementById("player").style.left, 10) || 0;
var plat1 = parseInt(document.getElementById("plat1").style.left, 10) || 0;
var width = player - plat1;
var elem = document.getElementById("player");
var pos = parseInt(document.getElementById("player").style.bottom, 10) || 0;
window.id = setInterval(frame, 5);
function frame() {
if(width > 100 && width < 164) {
if(gravity = true) {
pos--;
elem.style.bottom = pos + 'px';
if(elem.style.bottom = 0) {
clear();
}
}
}
}
function clear() {
clearInterval(id);
}}
How do I fix this. Thanks in advance.
You may not be clearing properly. Before setting interval clear any previously set one.
if(window.idl) clearInterval(window.idl);
window.idl = setInterval(framel, 5);

Snake Game with Mobile Button Controls

In this Snake game, I need the buttons to control the snake just like the arrow keys do. This will allow the game to be played on a mobile device. You can see i have code in there for the buttons, but they are not working properly and not controlling the movement of the snake.
Any advice to make the buttons work would be greatly appreciated! thanks!
HTML
<section class="game" id="share">
<div class="container">
<div class="columns twelve borders center">
<div class="game-container">
<div class="container">
<div class="SplashScreen">
<h1>
Snake
</h1>
<h2>
Click To Start.
</h2>
<input class="StartButton" type="button" value="Start" />
</div>
<div class="FinishScreen" style="display:none">
<h1>
Game Over
</h1>
<p>
Your score was: <span id="score"></span>
</p>
<input class="StartButton" type="button" value="Restart" />
</div>
<canvas id="canvasArea" height="300" width="300" style="display:none;"></canvas>
</div>
<div class="button-pad">
<div class="btn-up">
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-up.png" alt="Up" class="button up-btn" />
</div>
<div class="btn-right">
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-right.png" alt="Right" class="button right-btn" />
</div>
<div class="btn-down">
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-down.png" alt="Down" class="button down-btn" />
</div>
<div class="btn-left">
<input type="image" src="http://aaronblomberg.com/sites/ez/images/btn-left.png" alt="Left" class="button left-btn" />
</div>
</div>
</div>
</div>
</div>
</section>
JAVASCRIPT
( function( $ ) {
$( function() {
$(document).ready(function () {
$(".StartButton").click(function () {
$(".SplashScreen").hide();
$(".FinishScreen").hide();
$("#canvasArea").show();
init();
});
//Canvas stuff
var canvas = $("#canvasArea")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvasArea").width();
var h = $("#canvasArea").height();
//Lets save the cell width in a variable for easy control
var sw = 10;
var direction;
var nd;
var food;
var score;
//Lets create the snake now
var snake_array; //an array of cells to make up the snake
function endGame() {
$("#canvasArea").hide();
$("#score").text(score);
$(".FinishScreen").show();
}
function init() {
direction = "right"; //default direction
nd = [];
create_snake();
create_food(); //Now we can see the food particle
//finally lets display the score
score = 0;
//Lets move the snake now using a timer which will trigger the paint function
//every 60ms
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 60);
}
function create_snake() {
var length = 5; //Length of the snake
snake_array = []; //Empty array to start with
for (var i = length - 1; i >= 0; i--) {
//This will create a horizontal snake starting from the top left
snake_array.push({
x: i,
y: 0
});
}
}
//Lets create the food now
function create_food() {
food = {
x: Math.round(Math.random() * (w - sw) / sw),
y: Math.round(Math.random() * (h - sw) / sw),
};
//This will create a cell with x/y between 0-44
//Because there are 45(450/10) positions accross the rows and columns
}
//Lets paint the snake now
function paint() {
if (nd.length) {
direction = nd.shift();
}
//To avoid the snake trail we need to paint the BG on every frame
//Lets paint the canvas now
ctx.fillStyle = "#0056a0";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "#ffffff";
ctx.strokeRect(0, 0, w, h);
//The movement code for the snake to come here.
//The logic is simple
//Pop out the tail cell and place it infront of the head cell
var nx = snake_array[0].x;
var ny = snake_array[0].y;
//These were the position of the head cell.
//We will increment it to get the new head position
//Lets add proper direction based movement now
if (direction == "right") nx++;
else if (direction == "left") nx--;
else if (direction == "up") ny--;
else if (direction == "down") ny++;
//Lets add the game over clauses now
//This will restart the game if the snake hits the wall
//Lets add the code for body collision
//Now if the head of the snake bumps into its body, the game will restart
if (nx == -1 || nx == w / sw || ny == -1 || ny == h / sw || check_collision(nx, ny, snake_array)) {
//end game
return endGame();
}
//Lets write the code to make the snake eat the food
//The logic is simple
//If the new head position matches with that of the food,
//Create a new head instead of moving the tail
if (nx == food.x && ny == food.y) {
var tail = {
x: nx,
y: ny
};
score++;
//Create new food
create_food();
} else
{
var tail = snake_array.pop(); //pops out the last cell
tail.x = nx;
tail.y = ny;
}
//The snake can now eat the food.
snake_array.unshift(tail); //puts back the tail as the first cell
for (var i = 0; i < snake_array.length; i++) {
var c = snake_array[i];
//Lets paint 10px wide cells
paint_cell(c.x, c.y);
}
//Lets paint the food
paint_cell(food.x, food.y);
//Lets paint the score
var score_text = "Score: " + score;
ctx.fillStyle = "#ffffff";
ctx.fillText(score_text, 5, h - 5);
//Set the font and font size
ctx.font = '12px Arial';
//position of the fill text counter
ctx.fillText(itemCounter, 10, 10);
}
//Lets first create a generic function to paint cells
function paint_cell(x, y) {
ctx.fillStyle = "#d8d8d8";
ctx.fillRect(x * sw, y * sw, sw, sw);
}
function check_collision(x, y, array) {
//This function will check if the provided x/y coordinates exist
//in an array of cells or not
for (var i = 0; i < array.length; i++) {
if (array[i].x == x && array[i].y == y) return true;
}
return false;
}
// Lets prevent the default browser action with arrow key usage
var keys = {};
window.addEventListener("keydown",
function(e){
keys[e.keyCode] = true;
switch(e.keyCode){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
},
false);
window.addEventListener('keyup',
function(e){
keys[e.keyCode] = false;
},
false);
//Lets add the keyboard controls now
$(document).keydown(function (e) {
var key = e.which;
var td;
if (nd.length) {
var td = nd[nd.length - 1];
} else {
td = direction;
}
//We will add another clause to prevent reverse gear
if (key == "37" && td != "right") nd.push("left");
else if (key == "38" && td != "down") nd.push("up");
else if (key == "39" && td != "left") nd.push("right");
else if (key == "40" && td != "up") nd.push("down");
//The snake is now keyboard controllable
});
});
$(document).on('click', '.button-pad > button', function(e) {
if ($(this).hasClass('left-btn')) {
e = 37;
}
else if ($(this).hasClass('up-btn')) {
e = 38;
}
else if ($(this).hasClass('right-btn')) {
e = 39;
}
else if ($(this).hasClass('down-btn')) {
e = 40;
}
$.Event("keydown", {keyCode: e});
});
});
})( jQuery );
FIDDLE
AND TIME
So basically you have some errors going on. Your first one is your styling. You really need to make your styles more flexible, but this will solve the right button problem I was having.
.button-pad > div {
z-index: 9999;
width: 50px;
}
http://jsfiddle.net/34oeacnm/8/
$(document).on('click', '.button-pad .button', function(e) {
var e = jQuery.Event("keydown");
if ($(this).hasClass('left-btn')) {
e.which = 37;
}
else if ($(this).hasClass('up-btn')) {
e.which = 38;
}
else if ($(this).hasClass('right-btn')) {
e.which = 39;
}
else if ($(this).hasClass('down-btn')) {
e.which = 40;
}
$(document).trigger(e);
});
You had some of your selectors off. And I stole some information on how to trigger from Definitive way to trigger keypress events with jQuery.
Here is the code to add moile control to the snake game; (If you want the whole code for the snake game please comment);
//Here is javascript;
// left key
function l() {
if(snake.dx === 0) {
snake.dx = -grid;
snake.dy = 0;
}
}
// up key
function u() {
if(snake.dy === 0) {
snake.dy = -grid;
snake.dx = 0;
}
}
// right key
function r() {
if(snake.dx === 0) {
snake.dx = grid;
snake.dy = 0;
}
}
// down key
function d() {
if(snake.dy === 0) {
snake.dy = grid;
snake.dx = 0;
}
}
Here is HTML;
<div>
<button onclick="u()" type="button" id="U">U</button>
<button onclick="l()" type="button" id="L">L</button>
<button onclick="r()" type="button" id="R">R</button>
<button onclick="d()" type="button" id="D">D</button>
</div>
Description: I simply added four buttons in the html page, created four functions in the js which will move snake as it should move in different directions and simply added them to the 'onclick' attribute of the different buttons respectively.

-= operator in jQuery's css method not working in IE8

It looks like jQuery's handling of -= in css() isn't working in IE8 for some reason. The following code doesn't through any errors, but it doesn't work either. I've narrowed it down to the operator mentioned above.
var postCount = $(".postsWrapper .window .posts article").length;
var numberOfPages = Math.ceil(postCount / 3);
var currentPage = 1;
var transitioning = false;
$(".postsWrapper button").click(function() {
var direction = $(this).attr("data-direction");
var postWindowWidth = $(".postsWrapper .window").width();
if (direction == "next" && currentPage < numberOfPages && transitioning == false) {
transitioning = true;
// the below line does nothing in IE8
$(".postsWrapper .window .posts").css("marginLeft", "-=" + postWindowWidth);
setTimeout(function() {
transitioning = false;
}, 1000);
currentPage++;
} else if (direction == "previous" && currentPage > 1 && transitioning == false) {
transitioning = true;
// the below line does nothing in IE8
$(".postsWrapper .window .posts").css("marginLeft", "+=" + postWindowWidth);
setTimeout(function() {
transitioning = false;
}, 1000);
currentPage--;
}
});
See http://www.weblinxinc.com/beta/candy-controls/demo/site/index.htm
The problem is that your margin-left property is starting out with the value auto, and so jQuery can't increment/decrement it. Live Example (source below)
If you initially set it to a numeric value, it'll start working. Live example
This might qualify as a jQuery bug, you might check their list to see if it's there.
Here's the source to the live examples:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<div id="test">I'm the test div</div>
<script>
(function() {
"use strict";
// The following line is only in the second example, the one that works;
// without it, it doesn't work (in IE8) even though it does in Chrome
$("#test").css("marginLeft", 0);
var counter = 0;
var up = true;
display("Initial marginLeft: " + $("#test").css("marginLeft"));
setInterval(function() {
if (up) {
$("#test").css("marginLeft", "+=5");
} else {
$("#test").css("marginLeft", "-=5");
}
++counter;
if (counter > 10) {
counter =0;
up = !up;
}
}, 200);
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})();
</script>
</body>
</html>

Javascript touchEvents break Vertical Scrolling on iPad

I'm so close to getting this effect perfect, but I have run into a small little bump in the road.
I have a messaging system with a main div (#message-viewer) that contains a thread of messages. What I would like, is that when a user is viewing this on their iPad, and swipes to the right (anywhere inside this div), that #message-viewer slides off the screen and #div2 comes in from the left side of the screen.
Good News: The effect is smooth and responsive on the iPad. Javascript from Padalicious works like a charm.
Problems:
When the effect is on, my other jQuery functions do not work (for example, my buttons that open up a new div).
Vertical scrolling doesn't work! =(
I've tried:
In CSS on #swipeBox, I've tried all [overflow:] options to enable scrolling. No bueno.
I have tried attaching [ontouchstart=""] to the separate Divs, instead of creating a new one. No bueno.
I hope this makes sense... I have attached my code. I'm thinking the Padalicious code may be interfering with Y scrolling...
Thanks for the help!
HTML
<!DOCTYPE html>
<link rel="stylesheet" href="global/styles/base.css" type="text/css" />
<script src="global/js/jquery.tools.min.js"></script>
<script src="global/js/jquery.min.js"></script>
<script src="global/js/jquery-ui.min.js"></script>
<script src="global/js/jquery-1.5.js"></script>
<script src="global/js/ipad.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="minimum-scale=1.0, maximum-scale=1.0,
width=device-width, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
</head>
<body>
<div id="swipeBox" ontouchstart="touchStart(event,'message-viewer');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
<div id="content-container">
<div id="message-viewer">
// CONTENT HERE
</div>
<div class="Div2">
// CONTENT HERE
</div>
</div>
</div>
</body>
</html>
CSS
#swipeBox {
width: 100%;
height: auto;
}
JAVASCRIPT
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:
// <div id="picture-frame" ontouchstart="touchStart(event,'picture-frame');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
function touchStart(event,passedName) {
// disable the standard ability to select the touched object
event.preventDefault();
// get the total number of fingers touching the screen
fingerCount = event.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 == 2 ) {
// get the coordinates of the touch
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
// store the triggering element ID
triggerElementID = passedName;
} else {
// more than one finger touched so cancel
touchCancel(event);
}
}
function touchMove(event) {
event.preventDefault();
if ( event.touches.length == 2 ) {
curX = event.touches[0].pageX;
curY = event.touches[0].pageY;
} else {
touchCancel(event);
}
}
function touchEnd(event) {
event.preventDefault();
// check to see if more than one finger was used and that there is an ending coordinate
if ( fingerCount == 2 && 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);
}
}
function touchCancel(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;
}
function caluculateAngle() {
var X = startX-curX;
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); }
}
function determineSwipeDirection() {
if ( (swipeAngle <= 45) && (swipeAngle >= 0) ) {
swipeDirection = 'left';
} else if ( (swipeAngle <= 360) && (swipeAngle >= 315) ) {
swipeDirection = 'left';
} else if ( (swipeAngle >= 135) && (swipeAngle <= 225) ) {
swipeDirection = 'right';
}
}
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
// REPLACE WITH YOUR ROUTINES
$("#message-viewer").removeClass("slideright");
$('.Div2').removeClass("slideright");
} else if ( swipeDirection == 'right' ) {
// REPLACE WITH YOUR ROUTINES
$("#message-viewer").addClass("slideright");
$('.Div2').addClass("slideright");
}
}
The event.preventDefault(); block scrolling

Categories

Resources