How to switch cases by scrolling - javascript

How can I switch case by scrolling, and make it so that whenever you scroll up it changes cases one direction, and when you scroll down it changes the cases in the other direction? I hope that makes sense.
Here is how I did what I want to do using hotkeys, but this time I don't want to use hotkeys, I want to use the scrolling feature (I don't mean clicking on the scroll)
document.addEventListener('keydown', function (e) {
if (ws) {
switch (e.keyCode) {
// T
case 84:
if (player.items[ITEM_TYPE.WINDMAIL]) ws.send("42[\"5\"," + player.items[ITEM_TYPE.WINDMAIL].id + ",null]");
break;
// G
case 71:
e.stopPropagation();
if (player.items[ITEM_TYPE.SPIKES]) ws.send("42[\"5\"," + player.items[ITEM_TYPE.SPIKES].id + ",null]");
break;
// Z
case 90:
e.stopPropagation();
if (player.items[ITEM_TYPE.EXTRAS]) ws.send("42[\"5\"," + player.items[ITEM_TYPE.TURRET].id + ",null]");
break;
// F
case 70:
e.stopPropagation();
if (player.items[ITEM_TYPE.PITTRAP]) ws.send("42[\"5\"," + player.items[ITEM_TYPE.PITTRAP].id + ",null]");
break;
}
}
}, true);
and that works fine, but I want to make it so that is possible to do the same thing but my scrolling instead!
Can you help?

You can listen for scroll events using addEventListener (documented here: https://developer.mozilla.org/en-US/docs/Web/Events/scroll)
for example
window.addEventListener('scroll', function(e) {
// do something
});
or to capture scroll events on smaller box within your ui
document.querySelector('.my-scrollable-box').addEventListener('scroll', function(e) {
// do something
});
once you've done that you can keep track of the last know scroll position to determine if they scrolled up or down
var last_known_scroll_position = 0;
window.addEventListener('scroll', function(e) {
if (window.scrollY > last_known_scroll_position) {
// the user scrolled down
} else {
// the user scrolled up
}
last_known_scroll_position = window.scrollY;
}

Related

Detecting Left and Right Mouse Events for a Canvas Game

I want to implement a canvas minesweeper game using plain javascript. I use 2D array for my grid. For the game, I need to detect right and left mouse clicks, each of which will do different things. My research directed me towards mousedown, mouseup, contextmenu, however, my code does not seem to work, as for the right click it does the functions for both right and left click,because the mouseup event gets triggered for the right click as well. Can anyone help me understand how to distinguish between the two? I ran into examples of event.which, where left click is event.which === 0, and the right click is event.which === 2, but that works only for buttons, as far as I understood.
Here is the code.
canvas.addEventListener('mouseup', function(evt) {
let x1 = Math.floor(evt.offsetX/(canvas.height/rows));
let y1 = Math.floor(evt.offsetY/(canvas.width/cols));
draw (y1, x1); //this is my drawing functions (draws the numbers, bombs)
}, false);
canvas.addEventListener('contextmenu', function(evt) {
let j = Math.floor(evt.offsetX/(canvas.height/rows));
let i = Math.floor(evt.offsetY/(canvas.width/cols));
ctx.drawImage(flagpic, j*widthCell+5, i*widthCell+2, widthCell-9,
widthCell-5); //draws the flag where right mouse clicked
}, false);
Use click event for left click:
canvas.addEventListener('click', function(evt) { // No right click
And use contextmenu for right click: (Right click from keyboard context menu, also allowing you mouse right click)
canvas.addEventListener('contextmenu', function(evt) { // Right click
You need to call evt.preventDefault() as well for preventing the default action.
For your context, if you wanted to use mousedown or mouseup events, then you can use event.button to detect the clicked button was left:
canvas.addEventListener('mousedown', function(evt) {
if(evt.button == 0) {
// left click
}
Here's the button click values:
left button=0,
middle button=1 (if present),
right button=2
You can look on the example shown in the following link for greater details:
MouseEvent.button
<script>
var whichButton = function (e) {
// Handle different event models
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
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);
}
}
}
</script>
<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">
Click with mouse...
</button>
Try this might work for you
document.getElementById("mydiv").onmousedown = function(event) {
myfns(event)
};
var myfns = function(e) {
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
btnCode = e.button;
switch (btnCode) {
case 0:
console.log('Left');
break;
case 1:
console.log('Middle');
break;
case 2:
console.log('Right');
break;
}
}
}
<div id="mydiv">Click with mouse...</div>
Reference
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

Jquery multiple actions with same key based on position

I would like users to scroll down a list with the arrow down key. This is implemented.
Users should be able to load the next list when they hit down on the last item. This is also implemented.
I don't want users to be able to hold the down key from the top of one list and never let go, loading more and more lists at the bottom.
Is there a way for me to "push" a keyup event to the client, saying that once they've reached the bottom of a list they must manually push the down arrow key again?
Edit: Adding some code, in case it helps.
$(document).keydown(function(e) {
switch(e.which) {
case 40:
var lineID = Number($('.active').data('lineid'));
if(lineID != Number($('body > span').last().data('lineid'))) {
//update lineID to next number and activate next line
}
if(lineID == Number($('body > span').last().data('lineid'))) {
//update location to next list article
}
break;
default: return;
}
e.preventDefault();
});
What I need to do now, is somehow prevent a user from holding the down key and loading all lists after reaching the bottom. I would ideally think that "pushing" a key up event somehow would be satisfactory. As that would allow the user to scroll quickly to the bottom but then have to hit "down" again to load the next list, thereby making it easy to reach the bottom and prevent loading the next list by accident.
Use this code for that
// A variable to check when user is at the end of page
var endOfPage = false;
// keydown handler
$(document).keydown(function(e){
if(endOfPage==false){
// Do our thing
switch(e.keyCode){
case 40: // down
console.log('down');
break;
case 38: // up
console.log('up');
break;
}
}
});
$(window).on('scroll',function(){
if($(window).scrollTop() + $(window).height() == $(document).height()) {
//user is at the bottom of page
endOfPage = true;
}
});
// keyup handler
$(document).keyup(function(e){
endOfPage = false;
});

How Keyboard events of a desktop website are simulated in mobile website using jquery?

I have some function tied to keyboard arrow keys events in desktop website using JQuery.
$(document).keydown(function(e) {
switch (e.which) {
case 37: //left
doIT("leftside");
Break;
case 38: //up
doIT("upside");
Break;
case 39: //right
doIT("rightside");
Break;
case 40: //down
doIT("downside");
Break;
}
}
These are working fine on desktop website, but not on mobile website.
(I know we can't access arrow keys in mobile)
I want those corresponding functions to be executed in mobile website.
(if user swipes to left/up/right/down on mobile website)
can anyone help me in this?
I don't think you can do this, especially with swipes as swipes are a combination of different events (i.e. keydown, keyhold, keyup) .
Picking up swipes via keyup and keydown events can be very difficult. It would be better to use a plugin which can explicitly detect swipes such as Hammer.js
jquery mobile has events for swipeleft and swiperight
For up and down yo have to use the scrollstart and scrollstop events to detect in which direction the scroll is going.
var start = 0;
$(document).on("scrollstart", function() {
console.log($(window).scrollTop());
start = $(window).scrollTop();
});
$(document).on("scrollstop", function() {
console.log($(window).scrollTop());
var end = $(window).scrollTop();
if (start - end < 0) {
console.log("Scrolled down");
doIT("downside");
} else {
console.log("Scrolled up");
doIT("upside");
}
});
$(document).on("swipeleft", function() {
doIT("rightside");
console.log("right");
});
$(document).on("swipeleft", function() {
doIT("leftside");
console.log("right");
});

Adding buttons to a simple HTML5 game

I cant figure out a good way to add buttons to a simple HTML5 game that I'm trying to adapt for another use.
Instead of using the arrow keys to control the player, I want to have an actual 'up, down, left, right' buttons that have to be clicked (or more accurately, touched on a mobile device).
Here is the input code I'm trying to adapt.
input.js:
(function() {
var pressedKeys = {};
function setKey(event, status) {
var code = event.keyCode;
var key;
switch(code) {
case 32:
key = 'SPACE'; break;
case 37:
key = 'LEFT'; break;
case 38:
key = 'UP'; break;
case 39:
key = 'RIGHT'; break;
case 40:
key = 'DOWN'; break;
default:
// Convert ASCII codes to letters
key = String.fromCharCode(code);
}
pressedKeys[key] = status;
}
document.addEventListener('submit', function(e){
console.log(e);
return false;
})
document.addEventListener('keydown', function(e) {
setKey(e, true);
});
document.addEventListener('keyup', function(e) {
setKey(e, false);
});
window.addEventListener('blur', function() {
pressedKeys = {};
});
window.input = {
isDown: function(key) {
return pressedKeys[key.toUpperCase()];
}
};
})();
And here is the code from app.js that references the 'isDown' function:
function handleInput(dt) {
if(input.isDown('DOWN') || input.isDown('s')) {
player.pos[1] += playerSpeed * dt;
}
if(input.isDown('UP') || input.isDown('w')) {
player.pos[1] -= playerSpeed * dt;
}
if(input.isDown('LEFT') || input.isDown('a')) {
player.pos[0] -= playerSpeed * dt;
}
if(input.isDown('RIGHT') || input.isDown('d')) {
player.pos[0] += playerSpeed * dt;
}
}
I'm totally new to trying to make HTML5 games so any suggestions on how to handle touch / click events would be great. Also, for the buttons themselves, is it better to use divs, forms, or something else?
Thanks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Edit / Update:
So I inserted this into my app.js:
$("#upButton").click(function(){
console.log("click");
player.pos[1] -= playerSpeed * dt;
})
It actually registers the click event but it generates a really weird and random number of "clicks" (anywhere from a couple doze to thousands). The particular code I'm adapting can be found at this repo: https://github.com/jlongster/canvas-game-bootstrap
This guy's game is pretty neat but it has a lot "advanced" things for a noob to HTML5 games like me.
if it is button that is always visible - create button in html and add click event.
if you need dynamic button on canvas - you can draw button, and on mouse click check if mouse click in button area and button is visible/active, then execute your action.

Using arrow keys with jQuery scrollTo

I have successfully implemented the scrollTo jQuery plugin which scrolls to the next div with the class "new" when a link is clicked. However, I would also like to be able to use the arrow keys to scroll up and down to the next/previous divs of the same class.
I have looked all over the internet but have been unable to find out how to do this. I am very new to JS so very simple instructions would be appreciated!
Here is the relevant code:
<script type="text/javascript">
jQuery(function($){
$('<div id="next_arrow"></div>')
.prependTo("body") //append the Next arrow div to the bottom of the document
.click(function(){
scrollTop = $(window).scrollTop();
$('.new').each(function(i, h2){ // loop through article headings
h2top = $(h2).offset().top; // get article heading top
if (scrollTop < h2top) { // compare if document is below heading
$.scrollTo(h2, 800); // scroll to in .8 of a second
return false; // exit function
}
});
});
});
</script>
What do I need to add to this to make the arrow keys work?
Thanks,
Ted
You can use the keydown event listener to listen for keypresses. You can use this on <input> fields and the like. Because keydown events bubble up the DOM, you can use it on the document object to catch any keypress on the page:
$(function () {
$(document).keydown(function (evt) {
alert("Key pressed: " + evt.keyCode);
});
});
Each keypress has a code. If you use the code above in your web page, you'll see that the key code for the down arrow is 40. You can solo this out using an if or switch statement in the handler:
jQuery(function () {
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
alert("You pressed down.");
}
});
});
Now you need to bind in the code that actually jumps to the next heading. I recommend abstracting the code out into a function so you can use it for both keypresses and clicks. Here is the function, together with a variant of your original code that uses it:
// Here is the function:
function scrollToNew () {
scrollTop = $(window).scrollTop();
$('.new').each(function(i, h2){ // loop through article headings
h2top = $(h2).offset().top; // get article heading top
if (scrollTop < h2top) { // compare if document is below heading
$.scrollTo(h2, 800); // scroll to in .8 of a second
return false; // exit function
}
});
}
// Here is your original code, modified to use the function:
jQuery(function () {
$("#next").click(scrollToNew);
});
Finally, you can add in the keypress code and call the function from there:
function scrollToNew () {
scrollTop = $(window).scrollTop();
$('.new').each(function(i, h2){ // loop through article headings
h2top = $(h2).offset().top; // get article heading top
if (scrollTop < h2top) { // compare if document is below heading
$.scrollTo(h2, 800); // scroll to in .8 of a second
return false; // exit function
}
});
}
jQuery(function () {
$("#next").click(scrollToNew);
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
scrollToNew(); // scroll to the next new heading instead
}
});
});
Update: To scroll upwards, do two things. Change the keydown handler to:
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
scrollToNew(); // scroll to the next new heading instead
} else if (evt.keyCode == 38) { // up arrow
evt.preventDefault();
scrollToLast();
}
}
and write a scrollToLast() function based off of scrollToNew() that finds the last new heading that isn't on the page:
function scrollToLast () {
scrollTop = $(window).scrollTop();
var scrollToThis = null;
// Find the last element with class 'new' that isn't on-screen:
$('.new').each(function(i, h2) {
h2top = $(h2).offset().top;
if (scrollTop > h2top) {
// This one's not on-screen - make a note and keep going:
scrollToThis = h2;
} else {
// This one's on-screen - the last one is the one we want:
return false;
}
});
// If we found an element in the loop above, scroll to it:
if(scrollToThis != null) {
$.scrollTo(scrollToThis, 800);
}
}
Just for giving more idea, working with arrays.
var panel_arr = new Array();
$(document).ready(function(e) {
$('.parallax-panel-wrapper').each(function(i, element){
panel_arr.push( $(this).attr("id") );
});
var current_parallax_panel_no = 0;
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
if(current_parallax_panel_no < (panel_arr.length-1)) current_parallax_panel_no++;
scrollByArrowKeys(1);
} else if (evt.keyCode == 38) { // up arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
if(current_parallax_panel_no >= 1) current_parallax_panel_no--;
scrollByArrowKeys(0);
}
});
function scrollByArrowKeys(add_more){
scrollToThis = (($("#" + panel_arr[current_parallax_panel_no]).offset().top) + add_more ; // get element top
$.scrollTo(scrollToThis, 800);
}
});
You need to capture the keypress event and decide which keycode was pressed
$(document).keypress(function(e) {
switch(e.keyCode) {
case 37:
//left arrow pressed
break;
case 39:
//right arrow pressed
break;
}
});

Categories