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 ?
Related
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'))
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.
Hi,
I'm learning/practicing to make my custom slider in JS/JQuery, and I've written below code. Its almost running well but little issues. What I'm doing is I'm running it two types,
Auto running after each 5 seconds with autoRun() Function
On every click to slider indicator run to relevant slide with click event.
In below code, I'm facing couple of issues, and will be very thankful to you if you help me.
Issues I'm facing are:
When I click to slider indicator, I want to disable auto Run function for a specific time like 5 second so my slider look more professional.
When it goes to last slide or come back to first slide, console is showing an error below, and it also take double time eg: 10 seconds to go next slide.
"Uncaught TypeError: Cannot read property 'left' of undefined"
$(function () {
var $mainSliderWrap = $('#slider_main_wrapper')
, $sliderMain = $mainSliderWrap.find('.main-slider')
, $sliderchildren = $sliderMain.children('li')
, $sliderIndicator = $mainSliderWrap.find('.slider-main-indicator');
// Slider Setup
window.addEventListener('resize', initMainSlider);
initMainSlider();
// Slider SetUp function
function initMainSlider() {
var wWidth = window.outerWidth
, sliderMainWidth = wWidth * $sliderchildren.length
$sliderMain.css('width', sliderMainWidth + 'px');
$sliderMain.children('li').first().addClass('visible');
$sliderIndicator.children('li').first().addClass('active');
}
// Want to Run Slider on Click event
$sliderIndicator.on('click', 'li', updateMainSlider);
// If Click Event Not happenening then I want to auto run Slider after 5 seconds
autoRun()
function autoRun() {
var mainSliderChildLenght = $sliderchildren.length;
var i = 0;
var next = true;
var dir;
setInterval(function () {
if (mainSliderChildLenght == i || i < 0) {
next = !next;
if (i < 0) {
i = 0;
}
}
if (next) {
dir = 'next';
i++;
}
else {
dir = 'prev';
i--;
if(i < 0) {
return
}
}
updateMainSlider(dir);
$('#result').text(i)
}, 5000);
}
// Here is the function for Updating the Slider
function updateMainSlider(a) {
var visibleSlide = $sliderchildren.filter('.visible')
, actualTranslate = getTranslateValue($sliderMain, 'X');
if (a == 'next' || a == 'prev') { // inside this if is running when function is called from autoRun()
console.log(a)
var newSlide = (a == 'next') ? visibleSlide.next() : visibleSlide.prev()
, newSlideOffsetLeft = newSlide.offset().left
, valueToTranslte = -newSlideOffsetLeft + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
visibleSlide.removeClass('visible');
newSlide.addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq(newSlide.index()).addClass('active');
}
else { // inside this if is running when function is called from click event
console.log(a)
var newSlide = $(a.target)
, $newSlideIndicatorIndex = newSlide.index()
, $visibleSlideIndex = visibleSlide.index();
if ($newSlideIndicatorIndex !== $visibleSlideIndex && !$($sliderIndicator).hasClass('disable-click')) {
$($sliderIndicator).addClass('disable-click');
setTimeout(function () {
$($sliderIndicator).removeClass('disable-click');
}, 1000);
var diff = $newSlideIndicatorIndex - $visibleSlideIndex
, valueToTranslte = -(diff * window.outerWidth) + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
$($sliderchildren[$visibleSlideIndex]).removeClass('visible');
$($sliderchildren[$newSlideIndicatorIndex]).addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq($newSlideIndicatorIndex).addClass('active');
} // end if
} // end else
} // end function
// SetTranslate Value Fucntion
function setTranslateValue(element, property, value) {
$(element).css({
'transform': property + '(' + value + 'px)'
});
}
// Get Translate Value function
function getTranslateValue(element, axis) {
var trValue = $(element).css('transform');
if (trValue !== 'none') {
trValue = trValue.split(')')[0];
trValue = trValue.split(',');
trValue = (axis == 'X') ? trValue[4] : trValue[5];
}
else {
trValue = 0;
}
return Number(trValue);
}
})
ol {
list-style: none;
margin: 0;
padding: 0;
}
body {
margin: 0;
padding: 0;
}
.slider-main-wrapper {
box-shadow: inset 0 0 20px orange;
min-height: 100vh;
}
ol.main-slider {
height: 85vh;
box-shadow: inset 0 0 20px green;
transition: transform 500ms ease;
}
ol.main-slider > li {
float: left;
}
ol.main-slider > li .silder-main-content {
width: 100vw;
height: 85vh;
display: flex;
justify-content: center;
align-items: center;
}
ol.main-slider > li.visible .silder-main-content {
box-shadow: inset 0 0 140px green;
}
ol.slider-main-indicator {
height: 15vh;
display: flex;
}
ol.slider-main-indicator li {
box-shadow: inset 0 0 2px green;
flex: 1;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
ol.slider-main-indicator li.active {
box-shadow: inset 0 0 80px green;
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result" style="font-size: 30px; position: absolute;
top: 0; left: 0"></div>
<div class="slider-main-wrapper" id="slider_main_wrapper">
<ol class="main-slider">
<li>
<div class="silder-main-content">
<h1>First Slide</h1>
</div>
</li>
<li>
<div class="silder-main-content">
<h2>Second Slide</h2>
</div>
</li>
<li>
<div class="silder-main-content">
<h1>Third Slide</h1>
</div>
</li>
<li>
<div class="silder-main-content">
<h1>Fourth Slide</h1>
</div>
</li>
</ol>
<!--end slides-->
<ol class="slider-main-indicator">
<li> <span class="text">First Slide</span> </li>
<li> <span class="text">Second Slide</span> </li>
<li> <span class="text">Third Slide</span> </li>
<li> <span class="text">Fourth Slide</span> </li>
</ol>
<!--end slide indicator-->
</div>
you'll want to clearInterval when you click, the setInterval again once the processing due to the "click" event completes - so, for a start, you'll need to save the returned value of setInterval to use in clearInterval
autoRun in this code returns a function which starts the interval
this is just "part" of your code, not the whole thing - trying to keep it readable regarding the changes I have implemented
$sliderIndicator.on('click', 'li', updateMainSlider);
// save the function returned by autoRun
var go = autoRun();
// start autoRun
go();
// add a variable to store interval identifier
var interval;
function autoRun() {
var mainSliderChildLenght = $sliderchildren.length;
var i = 0;
var next = true;
var dir;
// return a function to begin autoRun for real
return function() {
// save interval identifier
interval = setInterval(function () {
// your code unchanged
}, 5000);
};
}
function updateMainSlider(a) {
var visibleSlide = $sliderchildren.filter('.visible')
, actualTranslate = getTranslateValue($sliderMain, 'X');
if (a == 'next' || a == 'prev') {
// your code - unchanged
} else {
// clear interval
clearInterval(interval);
// your code - unchanged
// now add this to restart the interval
go();
}
}
You may still need to tweak some things, I haven't gone through your code in depth
as requested
$(function () {
var $mainSliderWrap = $('#slider_main_wrapper')
, $sliderMain = $mainSliderWrap.find('.main-slider')
, $sliderchildren = $sliderMain.children('li')
, $sliderIndicator = $mainSliderWrap.find('.slider-main-indicator');
// Slider Setup
window.addEventListener('resize', initMainSlider);
initMainSlider();
// Slider SetUp function
function initMainSlider() {
var wWidth = window.outerWidth
, sliderMainWidth = wWidth * $sliderchildren.length
$sliderMain.css('width', sliderMainWidth + 'px');
$sliderMain.children('li').first().addClass('visible');
$sliderIndicator.children('li').first().addClass('active');
}
// Want to Run Slider on Click event
$sliderIndicator.on('click', 'li', updateMainSlider);
// If Click Event Not happenening then I want to auto run Slider after 5 seconds
var go = autoRun();
// start autoRun
go();
var interval;
function autoRun() {
var mainSliderChildLenght = $sliderchildren.length;
var i = 0;
var next = true;
var dir;
return function() {
setInterval(function () {
if (mainSliderChildLenght == i || i < 0) {
next = !next;
if (i < 0) {
i = 0;
}
}
if (next) {
dir = 'next';
i++;
}
else {
dir = 'prev';
i--;
if(i < 0) {
return
}
}
updateMainSlider(dir);
$('#result').text(i)
}, 5000);
});
}
// Here is the function for Updating the Slider
function updateMainSlider(a) {
var visibleSlide = $sliderchildren.filter('.visible')
, actualTranslate = getTranslateValue($sliderMain, 'X');
if (a == 'next' || a == 'prev') { // inside this if is running when function is called from autoRun()
console.log(a)
var newSlide = (a == 'next') ? visibleSlide.next() : visibleSlide.prev()
, newSlideOffsetLeft = newSlide.offset().left
, valueToTranslte = -newSlideOffsetLeft + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
visibleSlide.removeClass('visible');
newSlide.addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq(newSlide.index()).addClass('active');
}
else { // inside this if is running when function is called from click event
clearInterval(interval);
console.log(a)
var newSlide = $(a.target)
, $newSlideIndicatorIndex = newSlide.index()
, $visibleSlideIndex = visibleSlide.index();
if ($newSlideIndicatorIndex !== $visibleSlideIndex && !$($sliderIndicator).hasClass('disable-click')) {
$($sliderIndicator).addClass('disable-click');
setTimeout(function () {
$($sliderIndicator).removeClass('disable-click');
}, 1000);
var diff = $newSlideIndicatorIndex - $visibleSlideIndex
, valueToTranslte = -(diff * window.outerWidth) + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
$($sliderchildren[$visibleSlideIndex]).removeClass('visible');
$($sliderchildren[$newSlideIndicatorIndex]).addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq($newSlideIndicatorIndex).addClass('active');
} // end if
go();
} // end else
} // end function
// SetTranslate Value Fucntion
function setTranslateValue(element, property, value) {
$(element).css({
'transform': property + '(' + value + 'px)'
});
}
// Get Translate Value function
function getTranslateValue(element, axis) {
var trValue = $(element).css('transform');
if (trValue !== 'none') {
trValue = trValue.split(')')[0];
trValue = trValue.split(',');
trValue = (axis == 'X') ? trValue[4] : trValue[5];
}
else {
trValue = 0;
}
return Number(trValue);
}
})
I'm trying to create my own "autocomplete", but when I type a letter (eg. w for word), then there's a splitsecond delay - enough to annoy the eye.
Here's my testcode:
CSS:
#txtSearchAutocomplete {
background-color: white !important;
position: absolute;
top: 0;
width: 100%;
font-size: 20px !important;
border: none !important;
color: gray;
}
#txtSearch {
background-color: transparent !important;
position: absolute;
top: 0;
width: 100%;
font-size: 20px !important;
border: none !important;
}
HTML:
<span style="position: relative; display: inline-block; width:100%; top: -18px;">
<input type="text" id="txtSearchAutocomplete" disabled >
<input type="text" id="txtSearch">
</span>
JS:
$(document).ready(function($) {
$("#txtSearch").focus();
$("#txtSearch").keyup(function(e) {
var autocomplete = ['word', 'excel'];
var $txtAutocomplete = $("#txtSearchAutocomplete");
var txt = $("#txtSearch").val().trim().toLowerCase();
$txtAutocomplete.val("");
if (txt == "") return;
for (i = 0; i < autocomplete.length; i++) {
var entry = autocomplete[i];
if (entry.indexOf(txt) == 0) {
$txtAutocomplete.val(entry);
break;
};
};
});
});
And a fiddle sample:
https://jsfiddle.net/25gwz1qu/1/
If you type in the letter w - delete it - type it again and so on, then you will notice a small delay. It might seam that the delay is a bit longer in IE.
Any idea how to get rid of this delay?
Thanks
The reason for the delay you are seeing is because the event triggers once the user lets go of the key. In that case, the oninput is the way to go. The event triggers when the textbox input changes.
$("#txtSearch").on('input', function(e) { ... })
Please take a look on my solution with comments that explain why I did those changes and here is a Working Fiddle.
On my machine the auto-complete is almost instant after those modifications.
$(document).ready(function($) {
// i had moved all selectors outside the function so the havy dom selection will happen only once
var autocomplete = ['word', 'excel'];
var $txtAutocomplete = $("#txtSearchAutocomplete");
var $searchElement = $("#txtSearch");
$searchElement.focus();
// In Jquery on works faster than on key up, cause user lets go of the key.
$searchElement.on('input',function(e) {
var txt = $searchElement.val().trim().toLowerCase();
// I had replaced the element to be a div and not a input cause the div element is much light weight and faster to draw for the browser
$txtAutocomplete.text("");
if (txt == "")
return;
for (i = 0; i < autocomplete.length; i++) {
var entry = autocomplete[i];
if (entry.indexOf(txt) == 0) {
$txtAutocomplete.text(entry);
break;
};
};
});
});
try this,
$(document).ready(function($) {
$("#txtSearch").focus();
$("#txtSearch").on('input',function(e) {
var autocomplete = ['word', 'excel'];
var $txtAutocomplete = $("#txtSearchAutocomplete");
var txt = $("#txtSearch").val().trim().toLowerCase();
$txtAutocomplete.val("");
if (txt == "") return;
for (i = 0; i < autocomplete.length; i++) {
var entry = autocomplete[i];
if (entry.indexOf(txt) == 0) {
$txtAutocomplete.val(entry);
break;
};
};
});
});
How does citicards.com implement the login ID text box with special mask?
When you type "johndoe" and focus out the textbox becomes "jo***oe"
Is there a HTML5 mask with pattern?
Here is a sample implementation of the desired behaviour using pure javascript. This is just for a sample. You may need to do length check etc before actually using substr
document.querySelector("input#accountName").addEventListener("blur", function() {
var value = this.value;
document.querySelector("#maskedAccountName").textContent=this.value.substr(0,2)+this.value.substr(2,value.length-2).replace(/./g,"*")+this.value.substr(this.value.length-2, this.value.length);
this.style.display = "none";
document.querySelector("#maskedAccountName").style.display = "block";
}, false);
document.querySelector("#maskedAccountName").addEventListener("click", function() {
this.style.display = "none";
document.querySelector("input#accountName").style.display = "block";
document.querySelector("input#accountName").focus();
}, false);
div#maskedAccountName {
border: 1px solid rgba(231, 231, 231, 0.67);
padding: 2px;
display: none;
border-top-style: inset;
-webkit-appearance: textfield;
background-color: white;
width: 120px;
}
<input type="text" id="accountName">
<div id="maskedAccountName">
</div>
The reason why I'm not changing the existing input value is I may not be able to read the original value when accessed inside the form submit. So i've created a hidden div which is shown in place of the original input element. You can style the div to be same as the input element using CSS.
You have to use JS/jQuery. First count how mush letters from start and end you wish to take off, then replace everything else with * and append to fake input field.
You can see that in action here (replace opacity to 0 to completely hide input field, display: none will not work here, because you have to click on input itself):
$(document).ready(function() {
$("#hField").focusin(
function() {
$('#hFieldSp').text($(this).val());
});
$("#hField").focusout(function() {
var start = '';
var end = '';
var value = $(this).val();
var stars = '';
if (value.length < 3) {
return;
}
if (value.length > 6) {
start = value.substring(0, 2);
end = value.substring(value.length - 2);
stars = '*'.repeat(Math.max(1, value.length - 4));
} else {
start = value.substring(0, 1);
end = value.substring(value.length - 1);
stars = '*'.repeat(Math.max(1, value.length - 2));
}
$('#hFieldSp').text(start + stars + end);
});
$(document).on('input paste change', '#hField', function() {
$('#hFieldSp').text($(this).val());
});
});
String.prototype.repeat = function(num) {
return new Array(num + 1).join(this);
}
.wrapper {
float: left;
position: relative;
}
#hField,
#hFieldSp {
width: 100px;
height: 30px;
line-height: 30px;
border: 1px solid #ddd;
}
#hField {
opacity: .2;
position: absolute;
left: 0;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div id="hFieldSp"></div>
<input type="text" id="hField" />
</div>
I would use a dummy input for the display. Then on blur, transfer the value to a hidden input and alter the text in the dummy. You might also want the reverse in place in case the user wants to alter the value: on focus, copy the value from the hidden input to the dummy. Here's a sample, no jQuery required, and if there are less than 5 characters in the input, it will make all *s instead.
var start = 0;
var end = 4;
var dummy_user = document.getElementById("user");
var actual_user = document.getElementById("hidden_user");
dummy_user.addEventListener("blur", function() {
actual_user.value = dummy_user.value;
if (dummy_user.value.length > 4) {
start = 2;
end = dummy_user.value.length - 2;
}
var val = "";
for (var i = 0; i < start; i++) {
val += dummy_user.value[i];
}
for (i = start; i < end; i++) {
val += "*";
}
for (i = end; i < dummy_user.value.length; i++) {
val += dummy_user.value[i];
}
dummy_user.value = val;
});
dummy_user.addEventListener("focus", function() {
this.value = actual_user.value;
});
<form action="">
<input type="text" name="user" id="user">
<input type="hidden" name="hidden_user" id="hidden_user" value="">
<input type="password" name="password">
<input type="submit" value="Sign in">
</form>