how to know if two objects are in the same position - javascript

I want to know if the first object is in the same position of the second object to alert a message.
I am trying to create a simple game to see if the falling object touches the object that I move with my keyboard to stop the game and write "game over".
var t = setInterval(move,50);
var b = document.getElementById("ball");
var u = document.getElementById('obj') ;
function move() {
var pob = parseInt(b.style.top);
if (pob + 30 >=350){
pob = 0;
var p = Math.floor(Math.random()*320);
b.style.left = p + "px";
}
pob += 10;
b.style.top=pob+"px";
var f = parseInt(b.style.top) ;
var box = parseInt(u.style.top);
if (f == box) {
alert("stop");
}
}

Something like this?
(Example from https://www.w3schools.com/graphics/game_obstacles.asp)
function touch(obj1,obj2) {
var myleft = obj1.offsetLeft;
var myright = obj1.offsetLeft+obj1.offsetWidth;
var mytop = obj1.offsetTop;
var mybottom = obj1.offsetTop+obj1.offsetHeight;
var otherleft = obj2.offsetLeft;
var otherright = obj2.offsetLeft+obj2.offsetWidth;
var othertop = obj2.offsetTop;
var otherbottom = obj2.offsetTop+obj2.offsetHeight;
return !((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright))
}
var b = document.getElementById("ball");
var u = document.getElementById('obj') ;
var s = document.getElementById('sep') ;
console.log(touch(b,u),touch(s,b))
<div id='ball'>b</div>
<div id='sep'>separator</div>
<div id='obj'>u</div>
EDIT:
And there is the full snippet:
var t = setInterval(move,50);
var b = document.getElementById("ball");
var u = document.getElementById('obj') ;
var pos = 10 ;
var posleft =100;
var divwidth = 300;
document.addEventListener('keydown', function(event)
{
if(event.keyCode == 37) {
posleft = posleft - pos ;
if (posleft<0) {posleft = 0;}
u.style.left=posleft+'px';
}
else if(event.keyCode == 39) {
posleft = posleft + pos;
if (posleft>divwidth) {posleft = divwidth}
u.style.left=posleft+'px';
}
});
function touch(obj1,obj2) {
var myleft = obj1.offsetLeft;
var myright = obj1.offsetLeft+obj1.offsetWidth;
var mytop = obj1.offsetTop;
var mybottom = obj1.offsetTop+obj1.offsetHeight;
var otherleft = obj2.offsetLeft;
var otherright = obj2.offsetLeft+obj2.offsetWidth;
var othertop = obj2.offsetTop;
var otherbottom = obj2.offsetTop+obj2.offsetHeight;
return !((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright))
}
function move() {
if (touch(b,u)) {
alert("stop");
clearInterval(t)
}else{
var pob = parseInt(b.style.top);
if (pob + 30 >=200){
pob = 0;
var p = Math.floor(Math.random()*320);
b.style.left = p + "px";
}
pob += 5;
b.style.top=pob+"px";
}
}
<div id="obj" style="position:absolute;left:100px;top:180px;border:solid green 1px;">obj</div>
<div id="ball" style="position:absolute;top:0px;border:solid red 1px;">ball</div>
You need to focus on the page (click it) to control the game!
I hope that this will help you!

Related

How to fix 'ReferenceError: hello is not defined' when it is

I'm trying to code a game and I want to make it so that when you click a button, it increases the number. My game is like a mining game and you click to get ores and at the top right is a box which tells you what you are mining and you can see what you are mining, except when I click the mine button, it comes with the error which says ReferenceError: hello is not defined. The function hello is the function which gives you the ores.
I have tried fixing up some other functions which give you helpers in exchange for help but it didn't change anything, also I checked on stack overflow, but there wasn't anything that could help me. (Keep in mind I am 10 years old)
HTML:
<div class="mwrapper">
<button id="minebutton" onclick="hello()">Mine!</button>
</div>
JavaScript:
//defining the vars.
var stonei = 0;
var deepness = 0;
var stone = 0;
var silveri = 0;
var silver = 0;
var goldi = 0;
var gold = 0;
var platinumi = 0;
var platinum = 0;
var diamondi = 0;
var diamond = 0;
var alexandritei = 0;
var alexandrite = 0;
var amethysti = 0;
var amethyst = 0;
var unobtaniumi = 0;
var unobtanium = 0;
var emeraldi = 0;
var emerald = 0;
var tubi = 0;
var tub = 0;
var blockN;
var block = 0;
var money = 0;
var stoneSold = 0;
var silverSold = 0;
var goldSold = 0;
var clickers = 0;
var moneyEver = 0;
var BpS = 0;
//defining element to shorten code later
var blockEl = document.getElementById("block");
var btxtEL = document.getElementById("btxt");
var moneyEl = document.getElementById("money");
//changing what the 'Block you are mining' says
var findBlock = function(b) {
if (b === 0) {
blockEl.style.backgroundColor = "grey";
btxt.innerHTML = "Stone";
blockN = "stone";
}
else if (b === 1) {
blockEl.style.backgroundColor = "silver";
btxt.innerHTML = "Silver";
blockN = "silver";
}
else if (b === 2) {
blockEl.style.backgroundColor = "gold";
btxt.innerHTML = "Gold";
blockN = "gold";
}
else if (b === 3) {
blockEl.style.backgroundColor = "rgb(90, 89, 89)";
btxt.innerHTML = "Platinum"
blockN = "platinum";
}
else if (b === 4) {
blockEl.style.backgroundColor = "rgb(185, 242, 255)";
btxt.innerHTML = "Diamond"
blockN = "diamond";
}
else if (b <= 10) {
btxt.innerHTML = "Not coded yet";
}
//hehe
else {
btxt.innerHTML = "WHAAAA?????????";
}
}
//adds materials to the left sidebar
var createBlock = function(b) {
if (b === 0) {
stonei += 1;
stone += 1;
document.getElementById("stonei").innerHTML = stonei;
document.getElementById("stone").innerHTML = stone;
}
else if (b === 1) {
silveri += 1;
silver += 1;
document.getElementById("silveri").innerHTML = silveri;
document.getElementById("silver").innerHTML = silver;
}
else if (b === 2) {
goldi += 1;
gold += 1;
document.getElementById("goldi").innerHTML = goldi;
document.getElementById("gold").innerHTML = gold;
}
else if (b === 3) {
platinumi += 1;
platinum += 1;
document.getElementById("platinumi").innerHTML = platinumi;
document.getElementById("platinum").innerHTML = platinum;
}
else if (b === 4) {
diamondi += 1;
diamond += 1;
document.getElementById("diamondi").innerHTML = diamondi;
document.getElementById("diamond").innerHTML = diamond;
}
//not coded rest
}
//From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
//for finding the block when you mine
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
//when you click the mine button it does this
var hello = function() {
if (deepness === stone + silver + gold + platinum + diamond && stone >= stonei && silver >= silveri && gold >= goldi && platinum >= platinumi && diamond >= diamondi && stoneSold == stone - stonei && moneyEver == money + clickers &&typeof hsjsahjkd === 'undefined' || hsjsahjkd === null) {
if (deepness <= 50) {
block = 0;
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 50, deepness < 150) {
block = getRandomInt(0, 2);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 150, deepness < 250) {
block = getRandomInt(0, 3);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 250, deepness < 350) {
block = getRandomInt(0, 4);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 350) {
block = getRandomInt(0, 5);
findBlock(block);
deepness += 1;
createBlock(block)
}
}
else {
btxt.innerHTML = "Cheater.";
stonei = 0;
deepness = 0;
stone = 0;
silveri = 0;
silver = 0;
goldi = 0;
gold = 0;
platinumi = 0;
platinum = 0;
diamondi = 0;
diamond = 0;
alexandritei = 0;
alexandrite = 0;
amethysti = 0;
amethyst = 0;
unobtaniumi = 0;
unobtanium = 0;
emeraldi = 0;
emerald = 0;
tubi = 0;
tub = 0;
stoneSold = 0;
silverSold = 0;
goldSold = 0;
clickers = 0;
moneyEver = 0;
BpS = 0;
console.log("You cheated. The game restarted.")
if (typeof hsjsahjkd == 'undefined') {
var hsjsahjkd = 1;
}
else {
hsjsahjkd += 1;
}
document.getElementById("cheat").innerHTML = hsjsahjkd;
}
}
Sorry, but the functions needed are quite long. If you want to see the whole code, go to megagames.me/games/mining.html
I expected the out put of hello() to increment some of the ores, but it gave ReferenceError: hello is not defined.
Make sure your JavaScript is linked in the head tag or above the button. Otherwise you'll be calling a function that doesn't exist yet. An easy way to remember is to think of it as a book, you read from top to bottom the same way JavaScript executes top to bottom.
Also, try using Let and Const instead of Var and try using Switch Cases instead of if else all over. :-)

How to infinity spin on slot machine jQuery and stop it after do some action?

I have 2 option in radio input
Tab screen to stop in 0.5 sec -> So I complete this solution.
Tab screen to stop immediately. I want it spin after I press the submit button and it stops after I tab the screen.
Here is my fiddle here: https://jsfiddle.net/7det89o6/3/
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
}
});
}
<script type="text/javascript">
var reeling_time = 500;
var stop_spinning_time_difference = 350;
var start_spinning_time = 0;
var currency_symbol = "$";
var isInfinity = false;
$(document).ready(function() {
$(document).on('show.bs.modal', '.modal', function() {
function valRadioFunc() {
var valRadio = $('input[name=radio]:checked', '#form-select').val();
return valRadio;
}
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
isInfinity = true;
// one click
$(".bg-img").one("click", function() {
reeling_time = 0;
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
}
});
});
});
function randGen() {
var minRange = 1;
var maxRange = 999;
var randNum = (Math.floor(Math.random() * maxRange) + minRange).toString();
if (randNum.toString().length == 3) {
return randNum;
} else if (randNum.toString().length == 2) {
return "0" + randNum;
} else if (randNum.toString().length == 1) {
reeling_time = 0;
return "00" + randNum;
}
}
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var w1 = 40;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var w2 = 40;
var r2 = x2 + w2;
if (r1 < x2 || x1 > r2) return false;
return true;
}
$.fn.slotMachine = function(my_number) {
var $parentSlot = this;
var hidden_reels_html = '';
var hidden_reels_array = [];
var numberFormat = function number_format(number) {
number = (number + '');
return number;
}
for (var $j = 0; $j <= 9; $j++) {
hidden_reels_array[$j] = "";
for (var $i = 0; $i <= 9; $i++) {
hidden_reels_array[$j] += '<div class="reel-symbol' + ($i == 0 ? ' reel-loop' : '') + '">' + (($j + $i) % 10) + '</div>';
}
}
var transformNumberToArrayPlusDollar = function(my_number) {
var my_scale = parseInt(my_number, 10) > 999 ? 0 : 2;
my_number = numberFormat(my_number, my_scale, ".", ",");
var my_number_array = my_number.split('');
// my_number_array.unshift(currency_symbol);
return my_number_array;
};
//Effect for the reel to go up and then down like it is pushed to spin
var effectBeforeSpin = function() {
$parentSlot.find('.main-reel-symbol').removeClass('reel-stop').addClass('reel-begin');
};
var slotMachine = function(my_number) {
var my_number_array = transformNumberToArrayPlusDollar(my_number);
var reels_html = '';
for (var $i = 0; $i < my_number_array.length; $i++) {
reels_html += '<div class="reel">' + hidden_reels_array[($i % 10)] + '</div>';
}
effectBeforeSpin();
var startSpinning = function() {
$parentSlot.html(reels_html);
var my_timer = reeling_time;
$.each(my_number_array, function(my_index, my_value) {
var next_value = /^[0-9]$/.test(my_value) ? (parseInt(my_value, 10) + 1) % 10 : "0";
var stopSpinning = function() {
$parentSlot.find('.reel:eq(' + my_index + ')')
.html("<div class='reel-symbol main-reel-symbol reel-stop'>" + my_value + "</div>")
.append("<div class='reel-symbol'>" + next_value + "</div>");
};
if(!isInfinity){
setTimeout(stopSpinning, my_timer);
}
my_timer += stop_spinning_time_difference;
});
};
setTimeout(startSpinning, start_spinning_time);
};
slotMachine(my_number);
return this;
};
$('.reel-container:first').slotMachine('00' + 1).toString();
</script>
I add one variable at top of JavaScript code.

js only execute at a certain time?

i write this code to make a basic game. The full html is:
<!DOCTYPE>
<html>
<head>
<title>The dodge game</title>
<link rel="stylesheet" type="text/css" href="normalize.css">
<link rel="stylesheet" type="text/css" href="index.css">
<script src="jquery.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="play-ground">
<div id="character"></div>
<div id="chaser"></div>
</div>
<button id="control-up" class="button">UP</button>
<button id="control-down" class="button">DOWN</button>
<button id="control-right" class="button">RIGHT</button>
<button id="control-left" class="button">LEFT</button>
</body>
</html>
the script :
$(document).ready (
function() {
var characterPositionLeft = 0;
var characterPositionTop = 0;
var chaserPositionLeft = 810;
var chaserPositionTop = 630;
var speed = 30;
var dspeed = 60;
var apoint = 5;
var testPositionLeft = function() {
if (chaserPositionLeft > characterPositionLeft) {
chaserPositionLeft -= 30;
var caLeft = chaserPositionLeft + 'px';
$('#chaser').css('margin-left', caLeft);
leftRight();
topBottom();
testEndGame();
console.log(chaserPositionLeft);
} else if (chaserPositionLeft < characterPositionLeft) {
chaserPositionLeft += 30;
var caLeft = chaserPositionLeft + 'px';
$('#chaser').css('margin-left', caLeft);
leftRight();
topBottom();
testEndGame();
console.log(characterPositionLeft);
}
}
var testPositionTop = function() {
if (chaserPositionTop > characterPositionTop) {
chaserPositionTop -= 30;
var caTop = chaserPositionTop + 'px';
$('#chaser').css('margin-top', caTop);
leftRight();
topBottom();
testEndGame();
console.log(chaserPositionTop);
} else if (chaserPositionTop < characterPositionTop) {
chaserPositionTop += 30;
var caTop = chaserPositionTop + 'px';
$('#chaser').css('margin-top', caTop);
leftRight();
topBottom();
testEndGame();
console.log(chaserPositionTop);
}
}
// left and right
var CacLeftPlus = chaserPositionLeft + 30;
var CacLeftMinus = chaserPositionLeft - 30;
var LeftCaught = false;
// top and bottom
var CacTopPlus = chaserPositionTop + 30;
var CacTopMinus = chaserPositionTop - 30;
var TopCaught = false;
// up
$('#control-up').click (
function() {
testPositionTop();
if(characterPositionTop > 0) {
characterPositionTop -= speed;
var cTop = characterPositionTop + 'px';
console.log(characterPositionTop);
$('#character').css('margin-top', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached sky limit]');
}
}
)
// down
$('#control-down').click (
function() {
testPositionTop();
if(characterPositionTop < 630) {
characterPositionTop += speed;
var cTop = characterPositionTop + 'px';
console.log(characterPositionTop);
$('#character').css('margin-top', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached earth limit]');
}
}
)
// right
$('#control-right').click (
function() {
testPositionLeft();
if(characterPositionLeft < 810) {
characterPositionLeft += speed;
var cTop = characterPositionLeft + 'px';
console.log(characterPositionLeft);
$('#character').css('margin-left', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached right limit]');
}
}
)
// left
$('#control-left').click (
function() {
testPositionLeft();
if(characterPositionLeft > 0) {
characterPositionLeft -= speed;
var cTop = characterPositionLeft + 'px';
console.log(characterPositionLeft);
$('#character').css('margin-left', cTop);
leftRight();
topBottom();
testEndGame();
} else {
console.log('warning: [reached left limit]');
}
}
)
var leftRight = function() {
if(characterPositionLeft == CacLeftPlus || characterPositionLeft == CacLeftMinus) {
LeftCaught = true;
console.log('worked?');
} else {
}
}
var topBottom = function() {
if(characterPositionTop == CacTopPlus || characterPositionLeft == CacTopMinus) {
TopCaught = true;
console.log('worked?');
} else {
}
}
var testEndGame = function () {
if (LeftCaught == true && TopCaught == true) {
console.log('game over');
alert('game over');
} else {
}
}
}
)
Everything works fine until the functions leftRight, upBottom and testEndGame. They only console worked when the console is logged 600 and 630. Can anyone please tell me the flaw in this code and a way to fix this? Here is the full code: http://jsfiddle.net/StK7r/1/
I believe you want
if(characterPositionTop == CacTopPlus || characterPositionLeft == CacTopMinus) {
to instead test
if(characterPositionTop <= CacTopPlus && characterPositionTop >= CacTopMinus) {
because you intend your character to be caught inside a box. Same for left. Also, you were testing your 'top' position against your 'left'.
EDIT later:
I've updated the fiddle a bit. I noticed this also:
// left and right
var CacLeftPlus = chaserPositionLeft + 30;
var CacLeftMinus = chaserPositionLeft - 30;
var LeftCaught = false;
// top and bottom
var CacTopPlus = chaserPositionTop + 30;
var CacTopMinus = chaserPositionTop - 30;
You are not updating these variables when chaserPositionTop/Left changes. They are being bound by value here, so obviously they remained forever at the value you are giving them in the initializer.

Moving Up and down Options in Multiple select box

There is a logical error in the code..
we cannot move up or down 2 or more options at a time.Only 1 option at a time can be moved up or down..so how to make 2 or more options move up and down when selected...
function listbox_move(listID, direction) {
var listbox = document.getElementById(listID);
var selIndex = listbox.selectedIndex;
if(-1 == selIndex) {
alert("Please select an option to move.");
return;
}
var increment = -1;
if(direction == 'up')
increment = -1;
else
increment = 1;
if((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length-1)) {
return;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.selectedIndex = selIndex + increment;
}
And I call it as follows
listbox_move('countryList', 'up'); //move up the selected option
listbox_move('countryList', 'down'); //move down the selected option
Thank you in advance.... :)
I know its pretty old question... If it helps..
EDIT :
https://jsfiddle.net/m0f757wh/
<html>
<body>
<script language="javascript" type="text/javascript">
function moveUp()
{
var ddl = document.getElementById('contentlist');
//var size = ddl.length;
//var index = ddl.selectedIndex;
var selectedItems = new Array();
var temp = {innerHTML:null, value:null};
for(var i = 0; i < ddl.length; i++)
if(ddl.options[i].selected)
selectedItems.push(i);
if(selectedItems.length > 0)
if(selectedItems[0] != 0)
for(var i = 0; i < selectedItems.length; i++)
{
temp.innerHTML = ddl.options[selectedItems[i]].innerHTML;
temp.value = ddl.options[selectedItems[i]].value;
ddl.options[selectedItems[i]].innerHTML = ddl.options[selectedItems[i] - 1].innerHTML;
ddl.options[selectedItems[i]].value = ddl.options[selectedItems[i] - 1].value;
ddl.options[selectedItems[i] - 1].innerHTML = temp.innerHTML;
ddl.options[selectedItems[i] - 1].value = temp.value;
ddl.options[selectedItems[i] - 1].selected = true;
ddl.options[selectedItems[i]].selected = false;
}
}
function moveDown()
{
var ddl = document.getElementById('contentlist');
//var size = ddl.length;
//var index = ddl.selectedIndex;
var selectedItems = new Array();
var temp = {innerHTML:null, value:null};
for(var i = 0; i < ddl.length; i++)
if(ddl.options[i].selected)
selectedItems.push(i);
if(selectedItems.length > 0)
if(selectedItems[selectedItems.length - 1] != ddl.length - 1)
for(var i = selectedItems.length - 1; i >= 0; i--)
{
temp.innerHTML = ddl.options[selectedItems[i]].innerHTML;
temp.value = ddl.options[selectedItems[i]].value;
ddl.options[selectedItems[i]].innerHTML = ddl.options[selectedItems[i] + 1].innerHTML;
ddl.options[selectedItems[i]].value = ddl.options[selectedItems[i] + 1].value;
ddl.options[selectedItems[i] + 1].innerHTML = temp.innerHTML;
ddl.options[selectedItems[i] + 1].value = temp.value;
ddl.options[selectedItems[i] + 1].selected = true;
ddl.options[selectedItems[i]].selected = false;
}
}
</script>
<select id="contentlist" name="itemId" multiple="multiple">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button id="Up" onclick="moveUp()">Up</button>
<button id="Down" onclick="moveDown()">Down</button>
</body>
</html>
You need to loop through all options and test for which ones are selected and execute the same logic. Here is a working example of how to do it - you should be able to use this:
function listbox_move(listID, direction)
{
var listbox = document.getElementById(listID);
for(var i=0; i<listbox.options.length; i++)
{
var option = listbox.options[i];
if(option.selected == true)
{
var selIndex = i;
if(-1 == selIndex) {
alert("Please select an option to move.");
return;
}
var increment = -1;
if(direction == 'up')
increment = -1;
else
increment = 1;
if((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length-1)) {
return;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text
listbox.options[selIndex].selected = false;
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.options[selIndex + increment].selected = true;
}
}
}
There is an issue with dave823's answer, but I can't comment it, so there is my working solution:
You can't use same "for" loop (as you used it) in case of moving items upward and downward. You have to use two different loops for each case - something like this:
for(var i=0; i<listbox.options.length; i++)
for(var i = listbox.options.length - 1; i >= 0; i--)
Here is my (working) solution, based on dave823's answer:
function listbox_move(listBox, direction) {
if (direction == 'up') {
for (var i = 0; i < listBox.options.length; i++) {
moveLbSelectedItemUpDown(lbOutput, i, -1);
}
}
else if (direction == 'down') {
for (var i = listBox.options.length - 1; i >= 0; i--) {
moveLbSelectedItemUpDown(lbOutput, i, 1);
}
}
}
function moveLbSelectedItemUpDown(lb, itemIndex, increment) {
if (-1 == itemIndex) {
alert("Please select an option to move.");
return;
}
if (lb.options[itemIndex].selected == true) {
if ((itemIndex + increment) < 0 ||
(itemIndex + increment) > (lb.options.length - 1)) {
return;
}
var selValue = lb.options[itemIndex].value;
var selText = lb.options[itemIndex].text;
lb.options[itemIndex].value = lb.options[itemIndex + increment].value
lb.options[itemIndex].text = lb.options[itemIndex + increment].text
lb.options[itemIndex].selected = false;
lb.options[itemIndex + increment].value = selValue;
lb.options[itemIndex + increment].text = selText;
lb.options[itemIndex + increment].selected = true;
}
}
This is StackAddict's code with some important revisions to ensure Text and Value attributes are swapped together:
$("#up").bind("click", function () {
var ddl = $("[id*=lstRight]")[0]; // <-- you may not need the [0]... I needed it
var selectedItems = new Array();
for (var i = 0; i < ddl.length; i++)
if (ddl.options[i].selected)
selectedItems.push(i);
if (selectedItems.length > 0)
if (selectedItems[0] != 0)
for (var i = 0; i < selectedItems.length; i++) {
var tempText = ddl.options[selectedItems[i]].text;
var tempValue = ddl.options[selectedItems[i]].value;
ddl.options[selectedItems[i]].text = ddl.options[selectedItems[i] - 1].text;
ddl.options[selectedItems[i]].value = ddl.options[selectedItems[i] - 1].value;
ddl.options[selectedItems[i] - 1].text = tempText;
ddl.options[selectedItems[i] - 1].value = tempValue;
ddl.options[selectedItems[i] - 1].selected = true;
ddl.options[selectedItems[i]].selected = false;
}
});
$("#down").bind("click", function () {
var ddl = $("[id*=lstRight]")[0]; // <-- you may not need the [0]... I needed it
var selectedItems = new Array();
for (var i = 0; i < ddl.length; i++)
if(ddl.options[i].selected)
selectedItems.push(i);
if (selectedItems.length > 0)
if(selectedItems[selectedItems.length - 1] != ddl.length - 1)
for(var i = selectedItems.length - 1; i >= 0; i--)
{
var tempText = ddl.options[selectedItems[i]].text;
var tempValue = ddl.options[selectedItems[i]].value;
ddl.options[selectedItems[i]].text = ddl.options[selectedItems[i] + 1].text;
ddl.options[selectedItems[i]].value = ddl.options[selectedItems[i] + 1].value;
ddl.options[selectedItems[i] + 1].text = tempText;
ddl.options[selectedItems[i] + 1].value = tempValue;
ddl.options[selectedItems[i] + 1].selected = true;
ddl.options[selectedItems[i]].selected = false;
}
});

How to combine several pieces of code in one? (JavaScript)

i got a little problem with my code: i got 3 pieces of code, but i can't combine it together.
All three codes put timestamps in different cells when certain cells change.
If I change cell A1, then in cell B1 insert timestamp. If the change in cell A2, then in cell B2 insert timestamp , etc.
Can you help me? Thanks.
1)
function onEdit(event) {
var tsheet = 'Заявки' ;
var lcol = 17;
var rcol = 17;
var tcol = 18;
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn();
if (scol >= lcol && scol <= rcol) {
s.getRange(r.getRow(), tcol).setValue(new Date());
}
}
}
2)
function onEdit(event) {
var tsheet = 'Заявки' ;
var lcol = 15;
var rcol = 15;
var tcol = 16;
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn();
if (scol >= lcol && scol <= rcol) {
s.getRange(r.getRow(), tcol).setValue(new Date());
}
}
}
3)
function onEdit(event) {
var tsheet = 'Заявки' ;
var lcol = 9;
var rcol = 9;
var tcol = 8;
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn();
if (scol >= lcol && scol <= rcol) {
s.getRange(r.getRow(), tcol).setValue(new Date());
}
}
}
Put the column specification in an array:
function onEdit(event) {
var tsheet = 'Заявки' ;
var colspec=[[17,17,18],[15,15,16],[9,9,8]];
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn();
var i=colspec.length;
while (i>0) {
i--;
if (scol >= colspec[i][0] && scol <= colspec[i][1]) {
s.getRange(r.getRow(), colspec[i][2]).setValue(new Date());
}
}
}
}

Categories