How to move sprite diagonally with javascript? - javascript

I'm making a 2-D platformer style game with an HTML5 canvas. In it the character can jump and move side-to-side using the arrow keys, it works fine except for one problem. When I jump and move to the side at the same time the sprite goes up and doesn't move to the side. Only when it's coming down it moves properly. Is there a way to fix it? I've done research on other "move sprite diagonally" questions, but according to my code; when I let go of the 'up' key the sprite should move to the side, right? Take a look at my code and see what you think...
**note: act as if I've already defined the variables, because I have
window.addEventListener("keydown", checkKeyPressed, false);
//^don't proceed if you don't know what this means^
function checkKeyPressed(e) {
if (e.keyCode == "38" && jumpTime == 0) {
//checks if 'up' key is pressed then initiates the 'jump' sequence
refreshIntervalId = setInterval(jumpUp, 5);//calls the jump function
setTimeout(stopRefresh, 500);//sets time until character stops jumping
jumpCal();//temporarily disables jumping, and therefore a double-jump
}else if (e.keyCode == "37") {
//checks if 'left' key is pressed then moves sprite to the side
charX = charX - 8;//piece 1,
a = a - 8;//2,
c = c - 8;//and 3
}else if (e.keyCode == "39") {
//same thing, except to the right...
charX = charX + 8;
a = a + 8;
c = c + 8;
}
}
function jumpUp() {
charY = charY - 5;//moves up pieces 1,
b = b - 5;//2,
d = d - 5;//and 3, since the sprite is composed of three images
}
function stopRefresh() {
clearInterval(refreshIntervalId);
//stops the character from jumping
}
function jumpCal() {
jumpTime = 1;
setTimeout(jumpRes, 1750);
//times out the jumping action
}
function jumpRes() {
jumpTime = 0;
//resets the jumping action
}
function gravityControl() {
if (charY <= platformDetect) {
//checks if touching platform then moves all pieces down
charY = charY + 3;//piece 1
b = b + 3;//piece 2
d = d + 3;//piece 3
//this function is called multiple times in an unspecified piece of code, so no, I did not make an error here
}
}
function detectPlatform() {
platformDetect = 160;
//I've added this function because there will be platforms later in the game
}
Did you understand my code? Did I leave anything out? Was it too sloppy? If you have any suggestions not related to the question feel free to add it to the comments, I will accept any gladly.
Back to the topic on hand, was my code right? Because when I tap the 'up' key then let go and hold down on the 'right' key, my character's trajectory is as follows:
Step 1:
^
|
|
|
|
|
|
|
**Goes up fine, but doesn't move to side, as expected
Step 2:
|_
|_
|_
|_
|
|_
|
\ /
**Comes down and moves to side like it should
Can you help me please? If you didn't understand any part of my explanation I will accept criticism in the comments, after all I do want to become better.
_ _
|#| |#|
/_
---___ ___---
---_______---
**thnx in advance!!!

I didn't understand your code easily, I decided to write something from scratch, hope it can help. You might be interested in this answer as well: https://gamedev.stackexchange.com/a/29618/34073, and the related demo: http://jsfiddle.net/LyM87/.
// ex: if pressed[39] == true, walk to the right
var pressed = [];
// keyboard mapping
var keys = {
JUMP: 38,
RIGHT: 39,
LEFT: 37
};
// states of the black pixel
var pixor = {
el: $('#pixor'),
isJumping: false,
x: 10,
y: 0,
vy: 0,
vx: 0
}
// record user keystrokes
$(document).on('keydown keyup', function (e) {
pressed[e.which] = e.type === 'keydown';
e.preventDefault();
});
// classical game loop: update, render, redo after 1/60 sec
function loop () {
update();
render();
setTimeout(loop, 17);
}
// updates the states of the black pixel
function update () {
// vertical moves
if (!pixor.isJumping && pressed[keys.JUMP]) {
pixor.isJumping = true;
pixor.vy = 10;
}
if (pixor.isJumping) {
pixor.y += pixor.vy;
if (pixor.vy >= 0 && pixor.vy <= 0.5) {
pixor.vy = -0.5;
}
if (pixor.vy > 0) {
pixor.vy /= 1.25;
}
else {
pixor.vy *= 1.25;
}
if (pixor.y <= 0) {
pixor.isJumping = false;
pixor.y = 0;
pixor.vy = 0;
}
}
// horizontal moves
if (pressed[keys.RIGHT]) {
pixor.vx = 5;
}
else if (pressed[keys.LEFT]) {
pixor.vx = -5;
}
else {
pixor.vx = 0;
}
pixor.x += pixor.vx;
}
// repaints the screen based on the states of the black pixel
function render () {
pixor.el.css({
bottom: pixor.y,
left: pixor.x
});
}
body {
overflow: hidden;
}
#pixor {
position: absolute;
width: 40px;
height: 40px;
bottom: 0px;
left: 10px;
background: black;
}
#calltoaction {
position: absolute;
top: 0; right: 0;
bottom: 0; left: 0;
background: rgba(0,0,0,.5);
color: white;
text-align: center;
vertical-align: middle;
font: bold 24px Arial;
}
#calltoaction:after {
content: " ";
height: 100%;
display: inline-block;
vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pixor"></div>
<div id="calltoaction" onclick="$(this).remove();loop()">
Click here to start, then use UP, LEFT and RIGHT.
</div>

Since I don't have the full code, I can't be sure, but where you have else if (e.keyCode == "37") the else keyword is preventing moving side to side while holding jump.
Additionally, I recommend having a constant loop that handles movement rather than keypress event.
window.addEventListener("keydown", checkKeyPressed, false);
window.addEventListener("keyup", keyUp, false);
var jumpStarted = false;
var moveLeft = false;
var moveRight = false;
setInterval(function(){
if(leftDown === true)
//move Left
else if(rightDown === true)
//move Left
if(jumpStarted)
//Jump code
}, 10);
function checkKeyPressed(e) {
if (e.keyCode == "38" && jumpTime == 0) {
jumpStarted = true;
}if (e.keyCode == "37") {
moveLeft = true;
}else if (e.keyCode == "39") {
moveRight = true;
}
}
function keyUp(e){
if (e.keyCode == "37") {
moveLeft = false;
}else if (e.keyCode == "39") {
moveRight = false;
}
}
The benefit to this is that you move the entire time the key is down, not just when you press it. It also groups relative code together.

Related

Circle does not move right or down following arrow keypress

I want my code to do the following:
when the right arrow key is pressed, move the circle to the right
when the down arrow key is pressed, move the circle to the bottom
But instead it does the following:
When one of these keys is pressed, it moves only once and than no more. What am I doing wrong?
document.onkeydown = function(event) {
var circle = document.getElementById("circle");
if (event.keyCode == 39) {
circle.style.left += 100;
console.log("right")
} else if (event.keyCode == 40) {
circle.style.top += 100;
console.log("bottom")
}
}
#circle {
width: 50px;
height: 50px;
border-radius: 25px;
background: red;
position: absolute;
}
<div id="circle"></div>
You forgot about the units!
I changed your snippet to keep the actual values in 2 variables and added a function to update the circles style properties by using those vars and appending the units.
<html>
<head>
<title>HTML Test</title>
<style>
#circle {
width: 50px;
height: 50px;
border-radius: 25px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="circle"></div>
</body>
<script>
var circle = document.getElementById("circle");
var circleLeft = 0;
var circleTop = 0;
var updatePosition = function(left, top) {
circle.style.left = left + 'px';
circle.style.top = top + 'px';
};
// once at the start
updatePosition(circleLeft, circleTop);
document.onkeydown = function (event) {
if (event.keyCode == 39) {
circleLeft += 100;
console.log("right");
} else if (event.keyCode == 40) {
circleTop += 100;
console.log("bottom");
}
updatePosition(circleLeft, circleTop);
}
</script>
</html>
There is probably a more elegant way of doing this, but as
Rene said in the comments, you are dealing with strings not numbers and therefore will have trouble actually preforming simple operations like += 100. You instead need to substring the style string, parse the number from it and then add your number, then re-add the "px" to the end (actually might not be necessary since it seems to infer that 100 == 100px in HTML, but not the other way around.)
Here is a fix that worked for moving it left!
<script>
circle.style.left = "0px";
document.onkeydown = function (event) {
var circle = document.getElementById("circle");
if (event.keyCode == 39) {
console.log(circle.style.left.substring(0,circle.style.left.length -2))
circle.style.left = (parseInt(circle.style.left.substring(0,circle.style.left.length -2)) + 100) + "px"
console.log(circle.style.left)
} else if (event.keyCode == 40) {
circle.style.top += 100;
console.log("bottom")
}
}
</script>
Here is the working example. I have set the 10px move position instead of 100px.
Here you can move the circle infinite times as well instead of the single move.
document.onkeydown = function (event) {
var circle = document.getElementById("circle");
if (event.keyCode == 39) {
for (let i = 0; i < 10; i++) {
(i => {
setTimeout(() => {
const left = window.getComputedStyle(circle).left;
circle.style.left = `${(+left.replace("px", "") + i * 2) %
window.innerWidth}px`;
}, 500);
})(i);
}
} else if (event.keyCode == 40) {
for (let j = 0; j < 10; j++) {
(i => {
setTimeout(() => {
const top = window.getComputedStyle(circle).top;
circle.style.top = `${(+top.replace("px", "") + j * 2) %
window.innerWidth}px`;
}, 500);
})(j);
}
}
}
#circle {
width: 50px;
height: 50px;
border-radius: 25px;
background: red;
position: absolute;
}
<div id="circle"></div>

else if not working in KeyCode events javascript

I am trying to make me character moving left and up and I think jump() and slideLeft()
functions are working properly and the problem is in the controller(e) function (else if (e.KeyCode===37)) . The first function is avaible but it isn't able to acces the second conditon function. Also, I would want to make the grid solid after I will make an slideRight() similar function ,so if my character is jumping on it, the platform would sustain the square . Has anyone any ideea for either of my questions ?
Code snippet:
var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;
function jump() {
if (isJumping) return
let timerUpId = setInterval(function() {
if (bottom > 250) {
clearInterval(timerUpId);
let timerDownId = setInterval(function() {
if (bottom < 0) {
clearInterval(timerDownId);
isJumping = false;
}
bottom -= 5;
square.style.bottom = bottom + 'px';
}, 20)
}
isJumping = true;
bottom += 30;
square.style.bottom = bottom + 'px';
}, 20)
}
function slideLeft() {
console.log('da');
isGoingLeft = true;
leftTimerId = setInterval(function() {
left -= 5;
square.style.left = left + 'px';
}, 20)
}
function controller(e) {
if (e.keyCode === 32)
jump();
else if (e.KeyCode === 37)
slideLeft();
}
document.addEventListener('keydown', controller);
.grid {
position: absolute;
background-color: chartreuse;
height: 20px;
width: 500px;
bottom: 100px;
left: 100px;
}
.square {
position: absolute;
background-color: darkblue;
height: 100px;
width: 100px;
bottom: 0px;
left: 150px;
}
`
<div class="grid"></div>
<div class="square"></div>
EDIT:
There is a typo:
The second time you've written KeyCode
function controller(e) {
if(e.keyCode===32) {
jump();
}
else if(e.keyCode===37) {
slideLeft();
}
}
I don't really understand what you mean by the second part of your question. If you want a character to have the ability to jump on a square, you'll have to implement a collision detection. Something like this:
if ( isNotOnGround() ) {
fall()
}

Why event listener not changing?

Code:
window.onload = function() {
var a = document.getElementById("q");
var b = 1;
function tri() {
a.style.width = "100px";
b++
if (b == 3) {
b--
}
return b;
}
function un() {
a.style.width = "40px"
if (b == 2) {
b--
}
};
if (b == 1) {
a.addEventListener("click", tri);
};
if (b == 2) {
a.addEventListener("click", un)
};
};
#q {
width: 40px;
height: 40px;
background-color: blue;
}
<div id="q"></div>
I don't know why but my code is not working. Is it possible to add two event listeners in one element? If yes, then please explain how. I tried a lot, but it's not working.
Your code is only adding one listener to the DIV. It's testing the value of b when the page is loaded, and adds the tri function as a listener. It never performs the addEventListener code again when the value of b changes.
You can add multiple event listeners to an element, but there's no need to do that in this case. Just write one event listener that checks a variable. To alternate the action, the function simply inverts the value of the variable.
window.onload = function() {
var a = document.getElementById("q");
var small = true; // Is the DIV small or big?
function change() {
if (small) { // If it's small, make it big
a.style.width = "100px";
} else { // Otherwise, make it small
a.style.width = "40px";
}
small = !small; // invert the value of the variable
}
a.addEventListener("click", change)
};
#q {
width: 40px;
height: 40px;
background-color: blue;
}
<div id="q"></div>
your program is stuck on the first function. you enter as 1, and you get stuck on three. I debugged your program into a tragic story. I call it lost to 3. click on the square for the tragedy to unfold.
var square = document.getElementById("q");
var b = 0;
function triun() {
if (b === 0) {
square.style.width = "100px";
b=1;
}
else if (b === 1) {
square.style.width = "40px"
b=0;
};
}
square.addEventListener("click", triun)
#q {
width: 40px;
height: 40px;
background-color: blue;
}
<div id="q"></div>
window.onload = function() {
var a = document.getElementById("q");
var b = 1;
function tri() {
console.log('I want to be 1 but I am fleeting, forever to be two, click once more for my story'+ b +'unfold')
a.style.width = "100px";
b++;
console.log(b,' wowe is me, am I 2 or am I 3. All I know, is I will be a tragedy of the click handler that will always fire before the comming of the un')
if (b == 3) {
b--
console.log('I am lost to enter as 3, never will I ever be that 1, lost in time to that fading binary dream I once was but am now', b);
}
return b;
}
function un() {
console.log(b)
a.style.width = "40px"
if (b == 2) {
b--
}
};
if (b == 1) {
console.log('I am that first "if", that very first time you dared to dream, what might have been had "un" been here',b )
a.addEventListener("click", tri);
};
if (b == 2) {
console.log('I am that poor un, I will never be, because 2 will never visit me ');
a.addEventListener("click", un)
};
};
#q {
width: 40px;
height: 40px;
background-color: blue;
}
<div id="q"></div>

Mousewheel scroll event fire only once per scroll-session [duplicate]

This question already has an answer here:
jQuery page scroll event logic -- how to throttle
(1 answer)
Closed 6 years ago.
I am trying to mimic the functionality of the following website: www.verbaasd.net. Each scrolling "session" will only trigger one action.
Each time a user scrolls down an action will happen depending on the status of variabel count. I only want this to happen ONCE per scroll. For example if a user has a Macbook with touchpad it will fire multiple times very vast. The count will go from 1 to 4 pretty much instantly. Is there a way to set a timeout or something so it stops for 0.5 sec when variabel count increases or decreases by 1?
Current code:
var count = 1;
$(window).on('mousewheel DOMMouseScroll', function(e) {
if (e.originalEvent.wheelDelta / 120 > 0) {
count -= 1;
} else {
count += 1;
}
if (count < 1) count = 1;
if (count > 4) count = 4;
switch (count) {
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
case 4:
// do something
break;
}
$(".cd-background-wrapper").attr("data-slide", count);
});
I recommend other way.
You should use 'preventDefault' and delay effect using setTimeout.
I wrote a simple prototype code below link.
(only tested on Chrome and safari)
http://codepen.io/nigayo/pen/PNEvmY
[HTML]
<body>
<div id="wrap">
<section>section A</section>
<section>section B</section>
<section>section C</section>
<section>section D</section>
</div>
</body>
[CSS]
body {
overflow: hidden;
height: 100%;
}
#wrap {
position: relative;
width: 100%;
height: 100%;
top: 0;
}
section {
width: 100%;
height: 600px;
}
section:nth-child(1) {
background: red;
}
section:nth-child(2) {
background: blue;
}
section:nth-child(3) {
background: green;
}
section:nth-child(4) {
background: magenta;
}
[JavaScript]
(function() {
var currentPanel = 1;
var wrap = $('#wrap');
var panelsize = 600;
var step = 10;
var interval = 1000;
var direction = 1;
var bAnimation = false;
function animation() {
setTimeout(function() {
var currentTop = parseInt(wrap.css("top"));
if (direction < 0) {
if (currentTop <= minValue) {
setTimeout(function() {
bAnimation = false;
}, interval);
return;
}
} else {
if (currentTop >= minValue) {
setTimeout(function() {
bAnimation = false;
}, interval);
return;
}
}
wrap.css({
"top": currentTop - step
});
animation();
}, 16);
}
$(window).bind('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if (bAnimation) return;
var currentTop = parseInt(wrap.css("top"));
if (event.originalEvent.wheelDelta < 0) {
//down scroll
minValue = currentTop - panelsize;
step = 10;
direction = -1;
} else {
//up scroll
minValue = currentTop + panelsize;
step = -10;
direction = 1;
}
console.log(minValue, bAnimation);
bAnimation = true;
animation();
});
})();
If you refer to my codes, you should use 'jquery animate function' or 'requestAnimationframe' for animation logic.
Answer thanks to A. Wolff. Using _.throttle with lodash.js did the trick! You can find more info here: https://css-tricks.com/the-difference-between-throttling-and-debouncing/

Detecting number input spinner click

I've got a simple number input with a min="1" and max="12" value set, this is used as an hour selector. I'd like it to cycle through the hours, so when you get to 12 and press the "up" arrow, it goes back to 1 and vice-versa as well.
Right now I have this mostly working:
var inputTimer = null;
function cycle(element) {
if (element.attributes.max && element.attributes.min) {
var prevVal = element.value;
inputTimer = setTimeout(function() {
if (prevVal === element.attributes.max.value) {
element.value = element.attributes.min.value;
} else if (prevVal === element.attributes.min.value) {
element.value = element.attributes.max.value;
}
}, 50);
}
}
$("input[type='number']")
.on("mousedown", function(e) {
//this event happens before the `input` event!
cycle(this);
}).on('keydown', function(e) {
//up & down arrow keys
//this event happens before the `input` event!
if (e.keyCode === 38 || e.keyCode === 40) {
cycle(this);
}
}).on('input', function(e) {
//this event happens whenever the value changes
clearTimeout(inputTimer);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" min="1" max="12" value="12" />
Working DEMO
The issue I have is that I can't find a way to detect if the arrow spinners in the input have been clicked, or just the input as a whole has been clicked. Right now it has an issue where it changes the value when you click anywhere in the field when the value is currently at 1 or 12
Is there a way to detect if the click event occurs on the spinners/arrows within the text field?
You have to handle the input event, like this:
$('[type=number]').on('input',function(){
this.value %= 12 ;
if( this.value < 1 )
this.value -= -12 ;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=number>
I searched a lot and it seems there is no way to natively detect that. That makes this one a very important question because I think this should be added to new versions of HTML.
There are many possible workarouds. They all fail on the problem the it's impossible to know, in which direction is value going. I decided to use mouse position information to detect, whether is user increasing or decreasing a value. It works, but does not properly handle the situation, when user holds the button.
var inputTimer = null;
function cycle(event) {
var value = this.value;
// Value deep within bonds -> no action
if(value>this.min && value<this.max) {
return;
}
// Check coordinate of the mouse
var x,y;
//This is the current screen rectangle of input
var rect = this.getBoundingClientRect();
var width = rect.right - rect.left;
var height = rect.bottom-rect.top;
//Recalculate mouse offsets to relative offsets
x = event.clientX - rect.left;
y = event.clientY - rect.top;
// Now let's say that we expect the click only in the last 80%
// of the input
if(x/width<0.8) {
console.log("Not click on arrows.", x, width);
return;
}
// Check "clicked button" by checking how high on input was clicked
var percentHeight = y/height;
// Top arrow was clicked
if(percentHeight<0.5 && value==this.max) {
this.value = this.min;
event.preventDefault();
return false;
}
// Bottom arrow was clicked
if(percentHeight>0.5 && value==this.min) {
this.value = this.max;
event.preventDefault();
return false;
}
}
var input = document.getElementById("number");
input.addEventListener("mousedown", cycle);
<input id="number" type="number" min="1" max="12" value="12" />
A method you could try is by using the Attributes of the element to track what the previous value is. This isn't, of course, actually tracking which button got hit but it's the closest I've been able to get.
JS:
$(document).ready(function() {
function Init(){
var test = document.getElementById('test');
test.setAttribute('prev', 0);
}
Init()
$('#test').on('input', function() {
var test = document.getElementById('test')
var d = test.value - test.getAttribute('prev');
console.log(d);
test.setAttribute('prev', test.value);
});
});
HTML:
<input type="number" id="test">
Then all you would have is logic that says if d(irection) is positive, they clicked up. If negative, they clicked down. If it's 0 then they didn't click a button.
Working Fiddle
I think this is what you really want.
<input type="time" value="01:00" step="600"/>
There is currently no native way to capture the arrow input events separate from the input box events. Everything using number input seems to be kinda hacky for this purpose.
Next best option is something like http://jdewit.github.io/bootstrap-timepicker/
This doesn't work for your specific situation where you have a maximum and want it to wrap, but it might be helpful for others who want to process the field value based on changes via arrows, such as for setting .toFixed(2) to a currency value like I needed:
document.getElementById('el').setAttribute('data-last',document.getElementById('el').value);
document.getElementById('el').addEventListener('keyup', function(){
this.setAttribute('data-last',this.value);
});
document.getElementById('el').addEventListener('click', function(){
if(this.value>this.getAttribute('data-last')) console.log('up clicked');
if(this.value<this.getAttribute('data-last')) console.log('down clicked');
});
This is my code written in JQuery , this one can implement auto-increment ( + & - ) long-press spin buttons .
$.fn.spinInput = function (options) {
var settings = $.extend({
maximum: 1000,
minimum: 0,
value: 1,
onChange: null
}, options);
return this.each(function (index, item) {
var min = $(item).find('>*:first-child').first();
var max = $(item).find('>*:last-child').first();
var v_span = $(item).find('>*:nth-child(2)').find('span');
var v_input = $(item).find('>*:nth-child(2)').find('input');
var value = settings.value;
$(v_input).val(value);
$(v_span).text(value);
async function increment() {
value = Number.parseInt($(v_input).val());
if ((value - 1) > settings.maximum) return;
value++;
$(v_input).val(value);
$(v_span).text(value);
if (settings.onChange) settings.onChange(value);
}
async function desincrement() {
value = Number.parseInt($(v_input).val());
if ((value - 1) < settings.minimum) return;
value--
$(v_input).val(value);
$(v_span).text(value);
if (settings.onChange) settings.onChange(value);
}
var pressTimer;
function actionHandler(btn, fct, time = 100, ...args) {
function longHandler() {
pressTimer = window.setTimeout(function () {
fct(...args);
clearTimeout(pressTimer);
longHandler()
}, time);
}
$(btn).mouseup(function () {
clearTimeout(pressTimer);
}).mousedown(function () {
longHandler();
});
$(btn).click(function () {
fct(...args);
});
}
actionHandler(min, desincrement, 100);
actionHandler(max, increment, 100)
})
}
$('body').ready(function () {
$('.spin-input').spinInput({ value: 1, minimum: 1 });
});
:root {
--primary-dark-color: #F3283C;
--primary-light-color: #FF6978;
--success-dark-color: #32A071;
--sucess-light-color: #06E775;
--alert-light-color: #a42a23;
--alert-dark-color: #7a1f1a;
--secondary-dark-color: #666666;
--secondary-light-color: #A6A6A6;
--gold-dark-color: #FFA500;
--gold-light-color: #FFBD00;
--default-dark-color: #1E2C31;
--default-light-color: #E5E5E5;
}
.fx-row {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.fx-colum {
display: flex;
flex-direction: column;
flex-wrap: wrap;
}
.fx-colum.nowrap,
.fx-row.nowrap {
flex-wrap: nowrap;
}
.fx-row.fx-fill>*,
.fx-colum.fx-fill>* {
flex-grow: 1;
}
.spin-input {
border: 1px solid var(--secondary-light-color);
}
.spin-input>div:first-child {
cursor: pointer;
border-right: 1px solid var(--secondary-light-color);
}
.spin-input>div:first-child:active {
transform: translate3d(1px, 0px, 1px)
}
.spin-input>div:last-child {
flex: none;
border-left: 1px solid var(--secondary-light-color);
cursor: pointer;
}
.spin-input>div:last-child:active {
transform: translate3d(1px, 0px, 1px)
}
.icon {
font-weight: bold;
text-align: center;
vertical-align: middle;
padding: 12px;
font-size: 28px;
}
.icon.primary,
.icon.primary .ci {
color: var(--primary-dark-color);
}
.icon.reactive:hover .ci {
color: var(--primary-light-color);
}
.hidden {
display: none;
}
<script src="https://releases.jquery.com/git/jquery-3.x-git.min.js"></script>
<div class="spin-input nowrap fx-row fx-fill" >
<div class="icon reactive">
<span class="ci ci-minus">-</span>
</div>
<div class="icon">
<span>0</span>
<input type="text" class="hidden" value="0">
</div>
<div class="icon reactive">
<span class="ci ci-plus">+</span>
</div>
</div>
There is my jQuery plugin , I hope that can help you .
So I am not sure there is anyway to determine what is being clicked, be it field input or little arrows, but I was able to get it working like this.
Fiddle: http://jsfiddle.net/nusjua9s/4/
JS:
(function($) {
var methods = {
cycle: function() {
if (this.attributes.max && this.attributes.min) {
var val = this.value;
var min = parseInt(this.attributes.min.value, 10);
var max = parseInt(this.attributes.max.value, 10);
if (val === this.attributes.max.value) {
this.value = min + 1;
} else if (val === this.attributes.min.value) {
this.value = max - 1;
} else if (!(val > min && val < max)) {
// Handle values being typed in that are out of range
this.value = $(this).attr('data-default');
}
}
}
};
$.fn.circularRange = function() {
return this.each(function() {
if (this.attributes.max && this.attributes.min) {
var $this = $(this);
var defaultVal = this.value;
var min = parseInt(this.attributes.min.value, 10);
var max = parseInt(this.attributes.max.value, 10);
$this.attr('min', min - 1);
$this.attr('max', max + 1);
$this.attr('data-default', defaultVal);
$this.on("change", methods.cycle);
}
});
};
})(jQuery);
$("input[type='number']").circularRange();
HTML:
<input type="number" min="1" max="12" value="12" />
So I am not sure why I keep thinking about this and it still doesn't solve what you are seeing with the flash of out of range numbers which I don't see. But now its not confusing to setup the html ranges at least. You can set the range you want without thinking and just initialize the type="number" fields.
Try with $('input[type="number"]').change(function() {}); ? No result ?

Categories

Resources