Javascript: How to change class and CSS when value is zero - javascript

I have 9 boxes in my html.
There is a value, id called 'lifepoint'.
There is a mouse-click function: click once & decrease one life point. This code is completed.
function decrementlife() {
var element = document.getElementById('lifepoint');
var value = element.innerHTML;
--value;
console.log(value);
document.getElementById('lifepoint').innerHTML = value;
if(value <= 0) { alert("Game Over!")};
}
Also, there is a css style, called 'crackbox'.
.crackbox {
position: relative;
background: linear-gradient(0deg, black, rgb(120, 120, 120));
width: 12vh;
height: 12vh;
border-radius: 30%;
margin: 5px;
}
I want to change all box class from 'box' to 'crackbox' if life point is zero. Therefore, all box style can be 'crackbox'.
The below code is fail...
$(document).ready(function () {
$(".box").each(function() {
document.getElementById('lifepoint').innerHTML = value;
if(value <= 0) {
".box".toggleClass('crackbox')
};
})
});

Instead of using document ready, call another function from decrement life if the value turns 0. I am writing the code for your help.
function decrementlife() {
var element = document.getElementById('lifepoint');
var value = element.innerHTML;
--value;
console.log(value);
document.getElementById('lifepoint').innerHTML = value;
if(value <= 0) { changeClass(); alert("Game Over!")};
}
function changeClass(){
$('.box').addClass('crackbox').removeClass('box');
}
Hope, it helps!!

The simplest way would be to use querySelectorAll and loop through the elements:
for(let i = 0, list = document.querySelectorAll(".box"); i < list.length; i++)
{
list[i].classList.toggle('crackbox');
}
Or shorter ES6 version:
[...document.querySelectorAll(".box")].forEach(el => el.classList.toggle('crackbox'))

Related

What is causing div.style.right = '50%'; to stop being applied when my variable becomes greater than 0?

I have a variable count that triggers a function positiveBar if the value of count is > 0. If the value of count is < 0, it triggers a function negativeBar.
positiveBar changes a div's position using
progressBar.style.left = '50%';
negativeBar changes that same div's position using
progressBar.style.right = '50%';
This gives me the result I want; however, if at any point count becomes greater than 0, the positioning on negativeBar stops working, and it uses the positioning of the positiveBar function instead.
Video to explain:
var count = 0;
// Show count on the page
document.getElementById("countDisplay").innerHTML = count;
// Update count
function updateDisplay() {
countDisplay.innerHTML = count;
};
// Change negative count to an absolute
function absCount() {
return Math.abs(count);
};
function positiveBar() {
progressBar.style.backgroundColor = "#77eb90";
progressBar.style.width = (count * 10) + 'px';
progressBar.style.left = '50%';
};
function negativeBar() {
progressBar.style.backgroundColor = "#ef5c3f";
progressBar.style.width = (absCount() * 10) + 'px';
progressBar.style.right = '50%';
};
// Count up and down when + and - buttons are clicked and edit bar
add1.addEventListener("click", () => {
count++;
updateDisplay();
if (count > 0) {
positiveBar();
} else {
negativeBar();
}
});
subtract1.addEventListener("click", () => {
count--;
updateDisplay();
if (count > 0) {
positiveBar();
} else {
negativeBar();
}
});
.progressBar__Container {
height: 10px;
margin: 20px auto;
border: 1px solid black;
position: relative;
}
#progressBar {
height: 10px;
width: 0;
position: absolute;
}
<div id="countDisplay"></div>
<button id="add1">+</button>
<button id="subtract1">-</button>
<div class="progressBar__Container">
<div id="progressBar"> </div>
</div>
I tried reordering statements. I also tried creating a condition for if count = 0, but that didn't change the result. I'm very confused because it initially works how I intend, but if count becomes greater than 0 at any point, progressBar.style.right = '50%'; stops being applied.
You aren't clearing any previously set left or right styles when you switch from negative to positive and vice versa.
I would use CSS classes to control the position and colour as it's easier to toggle them based on the state of count.
let count = 0;
const countDisplay = document.getElementById("countDisplay");
const progressBar = document.getElementById("progressBar");
// Update count
function updateDisplay() {
countDisplay.textContent = count;
progressBar.style.width = `${absCount() * 10}px`;
progressBar.classList.toggle("positive", count > 0);
progressBar.classList.toggle("negative", count < 0);
};
// Change negative count to an absolute
function absCount() {
return Math.abs(count);
};
// Count up and down when + and - buttons are clicked and edit bar
add1.addEventListener("click", () => {
count++;
updateDisplay();
});
subtract1.addEventListener("click", () => {
count--;
updateDisplay();
});
.progressBar__Container {
height: 10px;
margin: 20px auto;
border: 1px solid black;
position: relative;
}
#progressBar {
height: 10px;
width: 0;
position: absolute;
}
#progressBar.positive {
background-color: #77eb90;
left: 50%;
}
#progressBar.negative {
background-color: #ef5c3f;
right: 50%;
}
<div id="countDisplay">0</div>
<button id="add1">+</button>
<button id="subtract1">-</button>
<div class="progressBar__Container">
<div id="progressBar"> </div>
</div>
See MDN:
When both left and right are defined, if not prevented from doing so by other properties, the element will stretch to satisfy both. If the element cannot stretch to satisfy both — for example, if a width is declared — the position of the element is over-constrained. When this is the case, the left value has precedence when the container is left-to-right; the right value has precedence when the container is right-to-left.
Because you are setting style.left when you then come to set style.right the above applies - i.e. the style.right setting will get overridden.

Food Ranking List Challenge (TestDome)

I get stuck on this challenge so I need help.
A website needs a list where users can rank their favorite foods.
Write the setup function, which should register click handlers on all
Up! and Down! buttons. The Up! button should move the list item one
place up in the list, while Down! button should move the list item one
place down in the list.
For example, consider this code:
document.body.innerHTML = `<ol>
<li><button>Up!</button>Taco<button>Down!</button></li>
<li><button>Up!</button>Pizza<button>Down!</button></li>
<li><button>Up!</button>Eggs<button>Down!</button></li>
</ol>`;
setup();
If the button Up! button in Pizza list item is clicked, Pizza should
be the first item in the list, while Taco should be the second item.
This is my current code:
function setup() {
let list = document.getElementByTagName('li');
let btnList = document.getElementByTagName('button');
let up;
let down;
for (let l = 0; l < list.length; l++){
for (let b = 0; b< btnList.length; b++){
btnList[b].addEventListener("click", (item, index)=>{
if(btnList[b].textContent == "Up!"){
up = list[l - 1]
} else if(btnList[b].textContent == "Down!"){
down = list[l + 1]
} else{
return list
}
})
}
}
return list;
})
}
}
I need to solve it without jQuery.
You don't need two for loops to iterate over the list elements and the buttons. You only need the buttons, the li elements are their parentNodes.
Moving up
Once you add the event listeners to every button, you can check if they are up or down buttons by checking their textContent. If it's an "up" button, you will need to check if it's the first element in the list. If it is, don't do anything, you can't move it any higher. :)
If it's not the first element, you can use insertBefore to swap nodes. Its first parameter is the node you want to insert, in this case the parent element; li. The second parameter is the reference; the node before which the li is inserted. That's the previousElementSibling of the parent.
Moving down
To move an element down is pretty similar. You probably think that you will use insertAfter to swap, but there is no insertAfter method. You can use insertBefore again, but this time the node you insert will be the nextElementSibling and the reference is the parent.
Check out the snippet below:
document.body.innerHTML = `<ol>
<li><button>Up!</button>Taco<button>Down!</button></li>
<li><button>Up!</button>Pizza<button>Down!</button></li>
<li><button>Up!</button>Eggs<button>Down!</button></li>
</ol>`
function setup() {
let btnList = document.querySelectorAll('button')
for (let button of btnList) {
button.addEventListener('click', handleClick)
}
}
function handleClick(e) {
let parent = e.target.parentElement
let isUp = e.target.textContent === 'Up!'
let isDown = e.target.textContent === 'Down!'
let isFirst = !parent.previousElementSibling
let isLast = !parent.nextElementSibling
if (isUp && !isFirst)
parent.parentNode.insertBefore(parent, parent.previousElementSibling)
if (isDown && !isLast)
parent.parentNode.insertBefore(parent.nextElementSibling, parent)
}
setup()
button {
background-color: hsl(206, 100%, 52%);
border: 0;
border-radius: 4px;
color: #fff;
cursor: pointer;
margin: 2px 4px;
padding: 4px 8px;
}
button:hover {
background-color: hsl(206, 100%, 40%);
}
You could also just add a single event listener on the ol element and check if the click target is a button. You can use event.target.tagName for this. If the tagName is BUTTON (always uppercase in HTML), you just return to exit early:
document.body.innerHTML = `<ol>
<li><button>Up!</button>Taco<button>Down!</button></li>
<li><button>Up!</button>Pizza<button>Down!</button></li>
<li><button>Up!</button>Eggs<button>Down!</button></li>
</ol>`
function setup() {
document.querySelector('ol').addEventListener('click', e => {
if (e.target.tagName !== 'BUTTON')
return
let parent = e.target.parentElement
let isUp = e.target.textContent === 'Up!'
let isDown = e.target.textContent === 'Down!'
let isFirst = !parent.previousElementSibling
let isLast = !parent.nextElementSibling
if (isUp && !isFirst)
parent.parentNode.insertBefore(parent, parent.previousElementSibling)
if (isDown && !isLast)
parent.parentNode.insertBefore(parent.nextElementSibling, parent)
})
}
setup()
button {
background-color: hsl(206, 100%, 52%);
border: 0;
border-radius: 4px;
color: #fff;
cursor: pointer;
margin: 2px 4px;
padding: 4px 8px;
}
button:hover {
background-color: hsl(206, 100%, 40%);
}
Use the code below
function setup() {
//Write your code here
$.fn.moveUp = function() {
before = $(this).prev();
$(this).insertBefore(before)
}
$.fn.moveDown = function() {
after=$(this).next();
$(this).insertAfter(after)
}
$("button:contains('Up!')").click(function() {
$(this).parent().moveUp()
})
$("button:contains('Down!')").click(function() {
$(this).parent().moveDown()
})
}
//Following code will give you 100% perfect score.
function setup() {
let buttons = document.querySelectorAll('button');
// console.log(buttons);
buttons.forEach(function(btn){
// console.log(btn);
btn.addEventListener("click", function(){
// console.log(btn.textContent);
if(btn.textContent.includes('Up!')){
// console.log(btn.parentElement.previousElementSibling);
// console.log(btn.parentElement.nextElementSibling);
if(btn.parentElement.previousElementSibling != null){
var store = btn.parentElement.previousElementSibling.innerHTML;
btn.parentElement.previousElementSibling.innerHTML= btn.parentElement.innerHTML;
btn.parentElement.innerHTML= store;
setup();
}else{ console.log("Hello Developer, this element is at start");}
}else{
// taking down.
if(btn.parentElement.nextElementSibling != null){
var stored = btn.parentElement.nextElementSibling.innerHTML;
btn.parentElement.nextElementSibling.innerHTML = btn.parentElement.innerHTML;
btn.parentElement.innerHTML = stored;
setup();
} else {
console.log("Hi developer, element already at last");
}
}
});
});
}
// Example case
document.body.innerHTML = `<ol>
<li><button>Up!</button>Taco<button>Down!</button></li>
<li><button>Up!</button>Pizza<button>Down!</button></li>
<li><button>Up!</button>Eggs<button>Down!</button></li>
</ol>`;
setup();
document.getElementsByTagName('button')[2].click();
console.log(document.body.innerHTML);

How can i change innerHTML +1?

I want to change the innerHTML so for every circle thats the same it adds +1
if (document.getElementById("circle1").style.backgroundColor == document.getElementById("circle5").style.backgroundColor) {
document.getElementById("point2").innerHTML = +1
}
if (document.getElementById("circle2").style.backgroundColor == document.getElementById("circle6").style.backgroundColor) {
document.getElementById("point2").innerHTML = +1
}
I suggest you to use innerText then. First get the old value and cast to Number then add by 1 and replace the old value. Example:
if (document.getElementById("circle1").style.backgroundColor == document.getElementById("circle5").style.backgroundColor) {
let obj = document.getElementById("point2");
let oldValue = Number(obj.innerText);
obj.innerText = oldValue + 1;
}
if (document.getElementById("circle2").style.backgroundColor == document.getElementById("circle6").style.backgroundColor) {
let obj = document.getElementById("point2");
let oldValue = Number(obj.innerText);
obj.innerText = oldValue + 1;
}
See difference between innerText and innerHtml.
document.getElementById("point2").innerHTML doesn't give you a number, so you cannot add 1 to it. first you need to parse the content to a number (like with parseInt or Number), and then you can add 1.
// creating the reference variable (for smaller code)
var point2 = document.getElementById("point2").innerHTML
if (document.getElementById("circle1").style.backgroundColor ==
document.getElementById("circle5").style.backgroundColor) {
document.getElementById("point2").innerHTML = increment(point2)
}
if (document.getElementById("circle2").style.backgroundColor ==
document.getElementById("circle6").style.backgroundColor) {
document.getElementById("point2").innerHTML = increment(point2)
}
// function to increment the value of point2
function increment(html) {
return Number(document.getElementById("point2").innerHTML) + 1
}
#circle1 {
background-color: red;
}
#circle5 {
background-color: red;
}
#circle2 {
background-color: red;
}
#circle6 {
background-color: red;
}
<div id="circle1">C1</div>
<div id="circle5">C5</div>
<br />
<div id="circle2">C2</div>
<div id="circle6">C6</div>
<div id="point2">0</div>

Variable values don't save in if loops

I'm attempting to create something that makes a button only work once. In order to do so, I created an if loop. In that if loop, I put it to a function called myFunction and then set a variable, button, to 0 (the if loop only runs if button is =2. It will not run in the first place. What am I doing wrong?
I've already attempted to recreate the variable(saying var button once out of the loop and then saying it again within).
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var button = 2;
var x = 0
function ins() {
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
x = getRndInteger(0, window.innerWidth)
alert(x);
}
function button() {
if (button === 2) {
alert("k")
myFunction();
button = 0;
} else {}
}
function myFunction() {
var para = document.createElement("SPAN");
para.style.position = "absolute";
x = getRndInteger(0, (window.innerWidth - 60))
para.style.left = x + "px"
var p = getRndInteger(0, (window.innerHeight - 60))
para.style.top = p + "px"
para.style.display = "inline-block;"
para.style.height = "50px"
para.style.width = "50px"
para.style.backgroundColor = "red"
para.style.borderRadius = "50px"
para.style.border = "1px solid black"
para.style.animation = "1s a linear"
para.id = "a"
para.onclick = myFunction
document.getElementById("myDIV").appendChild(para);
}
#keyframes a {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
button {
background-color: #010417;
border-radius: 10px;
border: 4px solid white;
color: white;
padding: 10px 26px;
font-size: 20px;
}
<div id="myDIV"></div>
<center>
<button id="button" onClick="button();">Start</button>
</center>
EDIT: Ignore the delete function, doesn't mean anything
The issue with this code is that your event handler function, and the flag (that changes value between 2 and 0) are both named 'button'. Javascript is a relatively accommodating language, so this kind of dual declaration might not throw error right away, but it will obviously cause unexpected behaviour.
Looking at your code:
var button = 2;
function button() {
if (button === 2) {
alert("k")
myFunction();
button = 0;
} else {}
}
In this case (depending on the JS engine), button either refers to the function or the number. If it's the number, then type error will be thrown when button is clicked. Since the code will try to call the number like a function.
If it's a function, then the button === 2 comparison will always be false, and the (empty) else block will get executed. Either way you wouldn't get the expected behavior. You can simply change the variable name to something else, and it should work.
Please note that, as someone pointed out in comments, you should prefer adding disabled attribute to the button over this logic. Unless the aim is to do something other than blocking multiple clicks of the button.

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