How to create a curved slider? - javascript

i'm trying to create a curved slider with jquery like this:
with no success.
can anyone point be to the right direction?
Thanks allot
Avi

This is what you want exactly. By using the jQuery roundSlider plugin you can make any type of arc slider with custom appearance.
Please check this jsFiddle for the demo of you requirement.
Live demo:
$("#arc-slider").roundSlider({
sliderType: "min-range",
circleShape: "custom-quarter",
value: 75,
startAngle: 45,
editableTooltip: true,
radius: 350,
width: 6,
handleSize: "+32",
tooltipFormat: function (args) {
return args.value + " %";
}
});
#arc-slider {
height: 110px !important;
width: 500px !important;
overflow: hidden;
padding: 15px;
}
#arc-slider .rs-container {
margin-left: -350px; /* here 350 is the radius value */
left: 50%;
}
#arc-slider .rs-tooltip {
top: 60px;
}
#arc-slider .rs-tooltip-text {
font-size: 25px;
}
#arc-slider .rs-border{
border-width: 0px;
}
/* Appearance related changes */
.rs-control .rs-range-color {
background-color: #54BBE0;
}
.rs-control .rs-path-color {
background-color: #5f5f5f;
}
.rs-control .rs-handle {
background-color: #51c5cf;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.roundslider/1.0/roundslider.min.js"></script>
<link href="https://cdn.jsdelivr.net/jquery.roundslider/1.0/roundslider.min.css" rel="stylesheet"/>
<div id="arc-slider" class="rslider"></div>
Screenshots of the Output:
To know more about the roundSlider, please check the demos and documentation page.

Please check this LINK, you will get enough details for the slider.
'slide': function(e, ui){
var percentLeft;
var submitValue;
var Y = ui.value - 100; //Find center of Circle (We're using a max value and height of 200)
var R = 100; //Circle's radius
var skip = false;
$(this).children('.ui-slider-handle').attr('href',' UI.val = ' + ui.value);
//Show default/disabled/out of bounds state
if ( ui.value > 0 && ui.value < 201 ) { //if in the valid slide rang
$(this).children('.ui-slider-handle').addClass('is-active');
}
else {
$(this).children('.ui-slider-handle').removeClass('is-active');
}
//Calculate slider's path on circle, put it there, by setting background-position
if ( ui.value >= 0 && ui.value <= 200 ) { //if in valid range, these are one inside the min and max
var X = Math.sqrt((R*R) - (Y*Y)); //X^2 + Y^2 = R^2. Find X.
if ( X == 'NaN' ) {
percentLeft = 0;
}
else {
percentLeft = X;
}
}
else if ( ui.value == -1 || ui.value == 201 ) {
percentLeft = 0;
skip = true;
}
else {
percentLeft = 0;
}
//Move handle
if ( percentLeft > 100 ) { percentLeft = 100; }
$(this).children('.ui-slider-handle').css('background-position',percentLeft +'% 100%'); //set new css sprite, active state
//Figure out and set input value
if ( skip == true ) {
submitValue = 'fail';
$(this).children('.ui-slider-handle').css('background-position',percentLeft +'% 0%'); //reset css sprite
}
else {
submitValue = Math.round(ui.value / 2); //Clamp input value to range 0 - 100
}
$('#display-only input').val(submitValue); //display selected value, demo only
$('#slider-display').text(submitValue); //display selected value, demo only
$(this).prev('.slider-input').val(ui.value); //Set actual input field val. jQuery UI hid it for us, but it will be submitted.
}
You can also try this LINK also.
If you want any other assistance, then please add comment.
Regards D.

Alternative way you can use this plugin for a curved/360 degree slider
Reference
Here is the coding:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/round-slider.min.js"></script>
<div class="box dotted">
<div class="left">
<div id="degrees" class="demo"></div>
</div>
<div class="right">
<p class="name">Degrees</p>
<p id="degrees-data"></p>
</div>
</div>
Javascript
(function($){
'use strict';
var set_html = function(value, index, angle, unit){
var html = ''
,val = value;
if(unit !== ''){
val += unit;
}
html += '<b>Value: </b>' + val + '<br/>';
html += '<b>Index: </b>' + index + '<br/>';
html += '<b>Angle: </b>' + angle + '<br/>';
return html;
};
$('document').ready(function(){
var self = {
degrees: null
};
self.degrees = $('#degrees').round_slider({
min: 0,
max: 359,
unit_sign: '\u00b0',
bg: 'img/bg/degrees-theme.png',
handle_bg: 'img/handles/wheel-33-33.png',
input_bg: 'img/input/round-50.png',
points_bg: 'img/points/degress-white.png',
angle_changed_callback: function(value, index, angle, unit){
$('#degrees-data').html(set_html(value, index, angle, unit));
}
});
});
})(jQuery);
Check here for the demo
Demo

Related

element not appends in body on window onload

I have been created the function which detects the screen zoom-in or zoom-out function. I am trying if window zoom == 100 or is in normal size the notification will remove else it append instantly.
In my code, it's working perfectly but it not working on window load, for showing the demo and result I have to click ctrl+ or ctrl-.
I am trying as window load it auto decide and append if window zoom, not 100 or normal.
Please help me with how I fix this?
function informationbar(percentage, zoomstatus) {
$("body").append('<div id="informationbar" style="top: 0px;"><img src="#" style="width: 14px; height: 14px; float: right; border: 0; margin-right: 5px" />You are using the window screen on ' + percentage + '% ' + zoomstatus + ' resolution, might some options are not visible properly on this current resolution please fit the screen on 100% as this our highly recommendation.</div>');
}
$(window).resize(function() {
var browserZoomLevel = Math.round(window.devicePixelRatio * 100);
if (browserZoomLevel !== '100') {
if (browserZoomLevel > "100") {
var status = "ZoomIn";
} else {
var status = "ZoomOut";
}
informationbar(browserZoomLevel, status);
} else {
$("div#informationbar").remove();
}
});
var browserZoomLevel = Math.round(window.devicePixelRatio * 100);
if (browserZoomLevel == '100') {
$("div#informationbar").remove();
} else {
if (browserZoomLevel > "100") {
var status = "ZoomIn";
} else {
var status = "ZoomOut";
}
informationbar(browserZoomLevel, status);
}
#informationbar {
position: fixed;
left: 0;
width: 100 %;
text - indent: 5 px;
padding: 5 px 0;
background - color: lightyellow;
border - bottom: 1 px solid black;
font: bold 12 px Verdana;
}
* html# informationbar {
/*IE6 hack*/
position: absolute;
width: expression(document.compatMode=="CSS1Compat" ? document.documentElement.clientWidth + "px": body.clientWidth + "px");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You seem to be using !== to compare numbers and strings, e.g. browserZoomLeveL !== '100' where browserZoomLevel = Math.round(...).
That will always give false, since the a string isn't a number, and === is strict about types. You should replace === '100' with just === 100.

progress bar increases as we press the button

I am new to programming but trying to solve a problem.
I am trying to increase a progress bar as I press on the "d" button. I am trying to do it recursively but I don't have enough skills to do it properly. Any help would be greately appreciated.
My js file looks like this so far:
window.addEventListener('keypress', function(e) {
function counter(p) {
//if the button is "d"
if (e.keyCode === 100) {
//target progressbar width and increase it
$('#progressbar').css('width', function(index, value) {
return $("#progressbar").css('width', ((p * 2) + "%"));
});
if ($('#progressbar').width() < 100) {
return counti(p + 1)
}
}
};
counti(1);
});
My html:
<div id = "myProgress" >
<div id = "progressbar" > 0 / 50 </div>
</div>
var count = 0;
var maxCount = 50;
var progressBar = document.getElementById("progressbar")
window.addEventListener("keypress", function(e) {
//if the button is "d"
if (e.keyCode === 100) {
// increase count if it's less than maxCount
count = count === maxCount ? maxCount : count + 1;
//target progressbar width and increase it
var newWidth = (count / maxCount) * 100 + "%";
progressBar.style.width = newWidth;
progressBar.innerHTML = count + "/" + maxCount
}
});
#myProgress {
width: 400px;
height: 30px;
background-color: #e4e4e4;
}
#progressbar {
width: 0%;
height: 30px;
background-color: #5980a7;
color: #fff;
}
<div id="myProgress">
<div id="progressbar">0/50</div>
</div>

Overlapping range inputs. On click change input with closest value

I have two overlapping range inputs, this creates a multi range input effect.
I want it so that whenever a click is made on either of these, the input with the closest value to the newly clicked value, is changed. Not entirely sure how to go about this.
How could I do this?
(function() {
"use strict";
var supportsMultiple = self.HTMLInputElement && "valueLow" in HTMLInputElement.prototype;
var descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
self.multirange = function(input) {
if (supportsMultiple || input.classList.contains("multirange")) {
return;
}
var values = input.getAttribute("value").split(",");
var max = +input.max || 100;
var ghost = input.cloneNode();
input.classList.add("multirange", "original");
ghost.classList.add("multirange", "ghost");
input.value = values[0] || max / 2;
ghost.value = values[1] || max / 2;
input.parentNode.insertBefore(ghost, input.nextSibling);
Object.defineProperty(input, "originalValue", descriptor.get ? descriptor : {
// Dang you Safari >:(
get: function() {
return this.value;
},
set: function(v) {
this.value = v;
}
});
Object.defineProperties(input, {
valueLow: {
get: function() {
return Math.min(this.originalValue, ghost.value);
},
set: function(v) {
this.originalValue = v;
},
enumerable: true
},
valueHigh: {
get: function() {
return Math.max(this.originalValue, ghost.value);
},
set: function(v) {
ghost.value = v;
},
enumerable: true
}
});
if (descriptor.get) {
// Again, fuck you Safari
Object.defineProperty(input, "value", {
get: function() {
return this.valueLow + "," + this.valueHigh;
},
set: function(v) {
var values = v.split(",");
this.valueLow = values[0];
this.valueHigh = values[1];
},
enumerable: true
});
}
function update() {
ghost.style.setProperty("--low", input.valueLow * 100 / max + 1 + "%");
ghost.style.setProperty("--high", input.valueHigh * 100 / max - 1 + "%");
}
input.addEventListener("input", update);
ghost.addEventListener("input", update);
update();
}
multirange.init = function() {
Array.from(document.querySelectorAll("input[type=range][multiple]:not(.multirange)")).forEach(multirange);
}
if (document.readyState == "loading") {
document.addEventListener("DOMContentLoaded", multirange.init);
} else {
multirange.init();
}
})();
#supports (--css: variables) {
input[type="range"].multirange {
-webkit-appearance: none;
padding: 0;
margin: 0;
display: inline-block;
vertical-align: top;
width: 250px;
margin-top: 50px;
margin-left: 50px;
background: lightblue;
}
input[type="range"].multirange.original {
position: absolute;
}
input[type="range"].multirange.original::-webkit-slider-thumb {
position: relative;
z-index: 2;
}
input[type="range"].multirange.original::-moz-range-thumb {
transform: scale(1);
/* FF doesn't apply position it seems */
G z-index: 1;
}
input[type="range"].multirange::-moz-range-track {
border-color: transparent;
/* needed to switch FF to "styleable" control */
}
input[type="range"].multirange.ghost {
position: relative;
background: var(--track-background);
--track-background: linear-gradient(to right, transparent var(--low), var(--range-color) 0, var(--range-color) var(--high), transparent 0) no-repeat 0 45% / 100% 40%;
--range-color: hsl(190, 80%, 40%);
}
input[type="range"].multirange.ghost::-webkit-slider-runnable-track {
background: var(--track-background);
}
input[type="range"].multirange.ghost::-moz-range-track {
background: var(--track-background);
}
}
<input type="range" multiple value="10,80" />
You'll have to capture a mouse event on the element and calculate how close it is to the high marker vs. the low marker and decide which one to update based on that. Also, because these are two stacked input elements, you'll probably have to pass the event to the low range input manually.
Here's my go at creating such a function:
function passClick(evt) {
// Are the ghost and input elements inverted? (ghost is lower range)
var isInverted = input.valueLow == ghost.value;
// Find the horizontal position that was clicked (as a percentage of the element's width)
var clickPoint = evt.offsetX / this.offsetWidth;
// Map the percentage to a value in the range (note, assumes a min value of 0)
var clickValue = max * clickPoint;
// Get the distance to both high and low values in the range
var highDiff = Math.abs(input.valueHigh - clickValue);
var lowDiff = Math.abs(input.valueLow - clickValue);
if (lowDiff < highDiff && !isInverted || (isInverted && lowDiff > highDiff)) {
// The low value is closer to the click point than the high value
// We should update the low value input
var passEvent = new MouseEvent("mousedown", {screenX: evt.screenX, clientX: evt.clientX});
// Pass a new event to the low "input" element (which is obscured by the
// higher "ghost" element, and doesn't get mouse events outside the drag handle
input.dispatchEvent(passEvent);
// The higher "ghost" element should not respond to this event
evt.preventDefault();
return false;
}
else {
console.log("move ghost");
// The high value is closer to the click point than the low value
// The default behavior is appropriate, so do nuthin
}
}
ghost.addEventListener("mousedown", passClick);
I put this code immediately above the input.addEventListener("input", update); line in your sample, and it seems to work. See my fiddle.
Some provisos though:
I only tested in Chrome. IE might have some trouble based on how I replicated the event. It may use a mechanism other than dispatchEvent... like fireEvent or something.
Initially I coded it assuming that the "ghost" element always kept track of the high range. I've since updated things to invert the event dispatching when the ghost element has the lower value--but I sped through it.
Here's something simple you could use. Although you might want to customize the style.
I am altering the z-index of the slider element based upon its proximity to the cursor.
JSFiddle
HTML
<input id='a' type='range' />
<input id='b' type='range' />
<label role='info'></label>
JS
var a = document.getElementById('a');
var b = document.getElementById('b');
a.onmousemove = function(e) {
MouseMove.call(a, e);
};
b.onmousemove = function(e) {
MouseMove.call(b, e);
};
var MouseMove = function(eventArg)
{
var max = parseInt(a.max),
min = parseInt(a.min),
diff = max - min,
clickPoint = eventArg.offsetX / a.offsetWidth,
clickPointVal = parseInt(diff * clickPoint) + min;
/* absolute distance from respective slider values */
var da = Math.abs(a.value - clickPointVal),
db = Math.abs(b.value - clickPointVal);
// Making the two sliders appear above one another only when no mouse button is pressed, this condition may be removed at will
if (!eventArg.buttons)
{
if (da < db)
{
a.style.zIndex = 2;
b.style.zIndex = 1;
}
else if (db < da)
{
b.style.zIndex = 2;
a.style.zIndex = 1;
}
}
document.querySelector('label').innerHTML = 'Red: ' + a.value + ', Green: ' + b.value + ', X: ' + eventArg.clientX;
}
CSS
input {
margin: 0px;
position: absolute;
left: 0px;
}
label {
display: inline-block;
margin-top: 100px;
}
#a {
z-index: 2;
}
#b {
z-index: 1;
}

How to color every second row using jQuery when the number of element in a row is variable?

Consider the following example which should color every second row: (live demo here)
JS:
$(function() {
var wrapper = $("<div></div>")
for (i = 0; i < 100; i++) {
wrapper.append("<span></span>");
}
$("body").append(wrapper);
color_rows();
});
function color_rows() {
$("span").each(function(i) {
if (i % 10 >= 5) {
$(this).css("background-color", "red");
}
});
}
CSS:
div {
width: 450px;
height: 400px;
background-color: #ccc;
overflow: auto;
}
span {
display: inline-block;
width: 50px;
height: 50px;
background-color: #777;
margin: 0 30px 30px 0;
}
The output is:
As you can see, color_rows() function assumes that there are 5 elements per row. If, for example, I change the width of the div to be 350px, the color_rows() function will not work properly (i.e. will not color every second row).
How could I fix color_rows() so that it will work for every width of the div ?
this is my solution:
this works based on the top offset of each element and by comparing the it to the top offset of last element in the loop it detects if new row is seen or not, and then based on the number of row colors rows.
function color_rows() {
var lastTop = -1;
var rowCount = 0;
$("span").each(function(i) {
var top = $(this).position().top;
if (top != lastTop) {
rowCount++;
lastTop = top;
}
if(rowCount % 2 == 0)
{
$(this).css("background-color", "red");
}
});
}
jsFiddle: http://jsfiddle.net/Ug6wD/4/
Look at my fixes http://jsfiddle.net/Ug6wD/5/
I am getting Container width, itemWidth + margin. And calculating how many items per row. Get margin-right from span item.
Then minus 20 to the container width, coz of overflow scrollbar.
function color_rows() {
var containerWidth = $('div').width()-20;
var itemWidth = $('span:first').width() + parseInt($('span:first').css('margin-right'));
var itemsPerRow = parseInt(containerWidth / itemWidth);
$("span").each(function(i) {
if (i % (itemsPerRow *2) >= itemsPerRow ) {
$(this).css("background-color", "red");
}
});
}
UPDATE with dynamic margin-right value from CSS AND Right scrollbar fix causing breakage : http://jsfiddle.net/Ug6wD/5/
Edit: This only works on some div-widths.. -.- Nevermind, then..
This should do it:
function color_rows() {
var divW = $('div').width();
var spanW = $('span').outerWidth(true); //Get margin too
var cnt = parseInt(divW/spanW, 10); //Remove decimals
$("span").each(function(i) {
if (i % (cnt*2) >= cnt) {
$(this).css("background-color", "red");
}
});
}
fiddle: http://jsfiddle.net/gn5QW/1/
html
<div id="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
js
$(document).ready(function(){
var box = $(".box");
var con = $("#container");
var box_per_line = Math.floor(parseInt($("#container").width())/ (parseInt( $(".box").width()) +10*2/*px*/));
var style = "black";
$(".box").each(function(i){
if(i % box_per_line == 0){ style = (style == "black") ? "grey" : "black"; }
$(this).css("background-color",style);
});
});
css
.box {
width: 100px;
height: 100px;
float: left;
margin: 10px;
}
#conainer {
background-color: grey;
display: inline-block;
}
I've fixed your code, but please PLEASE don't do this. The internet the in pain,
$(function() {
var wrapper = $("<div></div>")
for (i = 0; i < 100; i++) {
wrapper.append("<span></span>");
}
$("body").append(wrapper);
color_rows();
});
function color_rows() {
var rowWidth = Number( $('div:first').css('width').slice(0,-2) );
var itemWidth = Number( $('span:first').css('width').slice(0,-2) ) + Number( $('span:first').css('margin-right').slice(0,-2) );
var perRow = Math.floor( rowWidth/itemWidth );
$("span").each(function(i) {
if (i % 10 >= perRow ) {
$(this).css("background-color", "red");
}
});
}
There is a simpler way:
$('tr:even').css("background-color", "red");

how to move a div with arrow keys

I would like to move a div with my arrow keys using jQuery.
So right, left, down and up.
Found a demo of what I want to accomplish here
I would like to be able to move a div around in another div.
How can this be done?
var pane = $('#pane'),
box = $('#box'),
w = pane.width() - box.width(),
d = {},
x = 3;
function newv(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > w ? w : n;
}
$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });
setInterval(function() {
box.css({
left: function(i,v) { return newv(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
}, 20);
#pane {
position: relative;
width: 300px;
height: 300px;
border: 2px solid red;
}
#box {
position: absolute;
top: 140px;
left: 140px;
width: 20px;
height: 20px;
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pane">
<div id="box"></div>
</div>
Variable explanations:
w - the maximal left/top value that the box can have (to stay within bounds)
x - the distance (in px) that the box moves in each interval
d - this object stores the information on what key is being pressed. For instance, while the user holds down the LEFT ARROW key, d['37'] is true. Otherwise it's false. BTW, 37 is the key-code for the LEFT ARROW key and this value is stored in the e.which property of the event object. The d object is being updated on each keydown and keyup event.
An setInterval which is executed every 20ms, updates the left and top CSS properties of the box element. The new values are calculated via the newv function.
The newv function will calculate the new left/top value based on a) the old value v and b) the d object.
The expression n < 0 ? 0 : n > w ? w : n ensures that the new value is in the permitted bounds (which are 0 to w). If n is < 0, zero will be returned. If n is > w, w will be returned.
Live demo: http://jsfiddle.net/simevidas/bDMnX/1299/
Update: This code has the same functionality as the original code above. The only difference is that I used more meaningful names for my variables and arguments. As you can see, it looks awful - the original version is clearly better. :P
var pane = $('#pane'),
box = $('#box'),
maxValue = pane.width() - box.width(),
keysPressed = {},
distancePerIteration = 3;
function calculateNewValue(oldValue, keyCode1, keyCode2) {
var newValue = parseInt(oldValue, 10)
- (keysPressed[keyCode1] ? distancePerIteration : 0)
+ (keysPressed[keyCode2] ? distancePerIteration : 0);
return newValue < 0 ? 0 : newValue > maxValue ? maxValue : newValue;
}
$(window).keydown(function(event) { keysPressed[event.which] = true; });
$(window).keyup(function(event) { keysPressed[event.which] = false; });
setInterval(function() {
box.css({
left: function(index ,oldValue) {
return calculateNewValue(oldValue, 37, 39);
},
top: function(index, oldValue) {
return calculateNewValue(oldValue, 38, 40);
}
});
}, 20);
#Šime Vidas: Your first solution is simply marvelous. (i think the second one is redundant =)
May i suggest to make two different functions for the vertical and the horizontal width? Because it’s highly unlikely that you have to move around a div inside a perfect square and i believe it would be nicer to have something like this:
$(function () {
var pane = $('#pane'),
box = $('#box'),
wh = pane.width() - box.width(),
wv = pane.height() - box.height(),
d = {},
x = 5;
function newh(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > wh ? wh : n;
}
function newv(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > wv ? wv : n;
}
$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });
setInterval(function() {
box.css({
left: function(i,v) { return newh(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
}, 20);
});
This would have been exactly what i was looking for.
If you had a responsive design based on % values it would be recommendable to adjust your setInterval like this:
setInterval(function() {
box.css({
left: function(i,v) { return newh(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
wh = pane.width() - box.width();
wv = pane.height() - box.height();
}, 20);
if you do that it adjusts your panes height and width and the box still stops at its border.
i made a fiddle of that here http://jsfiddle.net/infidel/JkQrR/1/
Thanks a lot.
I can't see your demo, but here's a simple "move the box 1px in the direction of the arrow keys" example:
CSS:
#wrapper {
background-color: gray;
height:200px;
width: 200px;
position:absolute;
}
#mover {
background-color: white;
border: 1px solid red;
height:20px;
width: 20px;
position:relative;
}
Markup:
<div id="wrapper">
<div id="mover"></div>
</div>
JS (using jQuery):
$("#wrapper").keydown(function(event) {
var $mover = $("#mover");
//if nothing else will move "mover", then track the
//position instead of recalculating it every time:
// var moverPos = $mover.position();
// var left = moverPos.left;
// var top = moverPos.top;
var addTop = function(diff) {
$mover.css("top", ($mover.position().top + diff) + "px");
//if using tracked position:
// top += diff;
// $mover.css("top", top) + "px");
};
var addLeft = function(diff) {
$mover.css("left", ($mover.position().left + diff) + "px");
//if using tracked position:
// left += diff;
// $mover.css("left", left) + "px");
};
switch(event.keyCode) {
case 37: //left
addLeft(-1); break;
case 38: //up
addTop(-1); break;
case 39: //right
addLeft(1); break;
case 40: //down
addTop(1); break;
}
});
This is just an example, you may want to add bounds checking, larger movements, smoother animation, number pad support or any number of other things to it, but it should get you started.
try This Code
<html>
<head>
<style>
#ss{
background:#ccc;
height:100px;
width:100px;
position: absolute;
top: 0;
left: 0;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<div id="ss"></div>
</body>
<script type="text/javascript">
var $div = $('#ss');
$(document).keydown(function(e) {
switch (e.which) {
case 37:
$div.css('left', $div.offset().left - 10);
break;
case 38:
$div.css('top', $div.offset().top - 10);
break;
case 39:
$div.css('left', $div.offset().left + 10);
break;
case 40:
$div.css('top', $div.offset().top + 10);
break;
}
})
</script>
</html>

Categories