How to create Cash Register Effect using Pure Javascript? - javascript

I wanted to create a Cash Register Effect using Pure Javascript(With out using any libraries),
Here is the link for Cash register Effect which is implemented Using Mootools,
http://jsbin.com/ehuzes/edit#preview
I want to get this effect using raw Javascript. It will be huge help, If somebody gives the solution.

$('#number').on('change', function (e) {
$(this).cashregister($(this).val());
});
(function ($) {
$.fn.cashregister = function (num) {
var output = $('#output').html();
function intervalfunc(interval, num) {
var end = parseInt($('#number').html());
var cont = parseInt($('#output').html())
$('#output').html( cont + interval );
if ( $('#output').html() == num ) {
clearInterval(int);
return false;
}
}
if (num > output) {
var int = setInterval(function() { intervalfunc(1, num) }, 0.1);
}else if (num < output) {
var int = setInterval(function() { intervalfunc(-1, num) }, 0.1);
}else if (num == $('#output').html() ) {
// do nothing
}else{
alert("Invalid Input!");
}
};
})(jQuery);
http://jsfiddle.net/DuLjC/3/ -> working version of suggested fix

use an onclick function on a button or something, which should get the number (value from maybe a text box) and to send that variable to a defined function which uses .innerHTML on a div to change the number value, then you use SetInterval function to make the number go either up or down by 1 each interval. then use clearInterval when the number has been reached.
maybe something like:
<div id = "container">0</div>
<input type = 'text'
id = 'number' />
<input type = 'button'
value = 'change amount'
onclick = "var num = document.getElementById('number').value;
cashregister(num);" />
for the HTML and:
<script type = "text/javascript">
function cashregister(num) {
var cont = document.getElementById('container').innerHTML;
if (num < cont) {
var int = setInterval("intervalfunc(1)", (interval_time_in_miliseconds));
function intervalfunc(num) {
var end = document.getElementById('number');
var cont = document.getElementById('cont').innerHTML;
cont.innerHTML = cont + num;
if (cont == end) {
clearInterval(int);
}
}
} else if (num > cont) {
var int = setInterval("intervalfunc(-1)", (interval_time_in_miliseconds));
function intervalfunc(num) {
var end = document.getElementById('number');
var cont = document.getElementById('cont').innerHTML;
cont.innerHTML = cont + num;
if (cont == end) {
clearInterval(int);
}
}
} else if (num == cont) {
//do nothing
} else {
alert("invalid input!");
}
}
</script>
I'm not sure if this exact code will work but what you want is something along these lines.

I like this one by Nevan Scott: https://codepen.io/nevan/pen/uBkEr
var total = 0;
document.getElementById('entry').onsubmit = enter;
function enter() {
var entry = document.getElementById('newEntry').value;
var entry = parseFloat(entry);
currency = currencyFormat(entry);
document.getElementById('entries').innerHTML += '<tr><td></td><td>' + currency + '</td></tr>';
total += entry;
document.getElementById('total').innerHTML = currencyFormat(total);
document.getElementById('newEntry').value = '';
return false;
}
function currencyFormat(number) {
var currency = parseFloat(number);
currency = currency.toFixed(2);
currency = '$' + currency;
return currency;
}
body {
background: #EEE;
font-family: sans-serif;
font-size: 20px;
margin: 3em;
padding: 0;
}
#register {
width: 20em;
margin: auto;
}
#ticket {
background: white;
margin: 0 1em;
padding: 1em;
box-shadow: 0 0 5px rgba(0,0,0,.25);
}
#ticket h1 {
text-align: center;
}
#ticket table {
font-family: monospace;
width: 100%;
border-collapse: collapse;
}
#ticket td, #ticket th {
padding: 5px;
}
#ticket th {
text-align: left;
}
#ticket td, #ticket #total {
text-align: right;
}
#ticket tfoot th {
border-top: 1px solid black;
}
#entry {
background: #333;
padding: 12px;
border-radius: 10px;
box-shadow: 0 0 5px rgba(0,0,0,.25);
}
#entry input {
width: 100%;
padding: 10px;
border: 1px solid black;
text-align: right;
font-family: sans-serif;
font-size: 20px;
box-shadow: inset 0 0 3px rgba(0,0,0,.5);
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#entry input:focus {
outline: none;
border-color: rgba(255,255,255,.75);
}
<div id="register">
<div id="ticket">
<h1>Thank You!</h1>
<table>
<tbody id="entries">
</tbody>
<tfoot>
<tr>
<th>Total</th>
<th id="total">$0.00</th>
</tr>
</tfoot>
</table>
</div>
<form id="entry">
<input id="newEntry" autofocus placeholder="How Much?">
</form>
</div>

Related

Changing values in column in table using buttons

i would like create a table, where one column would be variables and i want to have "+" and "-" buttons next to it. So when i click button "+" it would show number input and after submit, it would add to the value.
It works for one value, but do not get the other right, without copying whole script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table</title>
</head>
<style>
body {
background-color: lightslategray;
}
#PLA {
float: left;
width: 30%;
padding: 10px;
}
th, td {
border: 1px solid;
}
.header {
text-align: center;
font-size: 20px;
}
.celltext {
font-size: 15px;
}
.number {
text-align: center;
}
.vbutton {
background-color: gray;
border: 1px solid black;
border-radius: 6px;
color: white;
text-align: center;
text-decoration: none;
font-size: 10px;
padding: 0px;
margin-right: 4px;
width: 20px;
height: 20px;
float: right;
}
button:hover {
background-color: lightgray;
color: black;
}
.input {
padding: 0px;
width: 48px;
height: 16px;
font-size: 14px;
-webkit-appearance: none;
}
input[type = number] {
-moz-appearance: textfield;
}
input:focus {
border: 0px;
outline: 0px;
}
</style>
<body>
<table id="PLA">
<div>
PLA
<span id="test"></span>
<input type="number" class="input" id="nwpla" onchange="changewpla1()" onkeypress="return onlyNumberKey(event)">
</div>
<tr class="header">
<td>Barva</td>
<td>Výrobce</td>
<td>Hmotnost (g)</td>
<td>Cena (kg)</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla1">
<span id="wpla1"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
<tr class="celltext">
<td>černá <div class="box black"></div></td>
<td>Polymaker PolyLite</td>
<td class="number" id="pla2">
<span id="wpla2"></span>
<button class="vbutton" onclick="addpla()"> + </button>
<button class="vbutton" onclick="subpla()"> - </button>
</td>
<td class="number">
800
</td>
</tr>
</table>
</body>
<script>
// test
test = document.getElementById("test");
// Weight of pla1
wpla1 = document.getElementById("wpla1");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla1weight = localStorage.pla1weight;
localStorage.setItem("pla1weight", pla1weight);
if (localStorage.pla1weight == "undefined" || localStorage.pla1weight == isNaN) {
localStorage.pla1weight = 0
pla1weight = 0;
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
else {
wpla1.innerHTML = localStorage.pla1weight;
wpla1.value = localStorage.pla1weight;
}
function changewpla1() {
x = parseInt(wpla1.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla1weight = x - y;
} else {
pla1weight = x + y;
}
wpla1.innerHTML = pla1weight;
wpla1.value = pla1weight;
localStorage.setItem("pla1weight", pla1weight);
nwpla.style.display = "none";
}
// Weight of pla2
wpla2 = document.getElementById("wpla2");
nwpla = document.getElementById("nwpla");
nwpla.style.display = "none";
var pla2weight = localStorage.pla2weight;
localStorage.setItem("pla2weight", pla2weight);
if (localStorage.pla2weight == "undefined" || localStorage.pla2weight == isNaN) {
localStorage.pla2weight = 0
pla2weight = 0;
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
else {
wpla2.innerHTML = localStorage.pla2weight;
wpla2.value = localStorage.pla2weight;
}
function changewpla2() {
x = parseInt(wpla2.value, 10);
y = parseInt(nwpla.value, 10);
if (p == 1) {
pla2weight = x - y;
} else {
pla2weight = x + y;
}
wpla2.innerHTML = pla2weight;
wpla2.value = pla2weight;
localStorage.setItem("pla2weight", pla2weight);
nwpla.style.display = "none";
}
function addpla() {
nwpla.value = 0;
p = 0;
nwpla.style.display = "";
}
function subpla() {
nwpla.value = 0
p = 1;
nwpla.style.display = "";
}
function onlyNumberKey(evt) {
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
}
</script>
</html>
Any idea?
I would like to have a database as last option. Every value would be saved in local storage.
Thanks.

Textarea which counting entered symbolys

function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
// var last2 = 100 - integer2;
if (symbolCount >= 100) {
document.querySelector('.hidden_block').style.color = 'green';
}
else if (symbolCount <= 100) {
document.querySelector('.hidden_block').style.color = 'black';
document.querySelector('.error').style.display = "block";
}
else {
document.getElementById('max').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
email.addEventListener("click", function(){
document.querySelector('.hidden_block').style.display = 'block';
document.getElementById('max').style.display = 'none';
});
#max, #max2 {
text-align: right;
margin-right: 55px;
}
.hidden_block {
display: none;
text-align: right;
margin-right: 55px;
}
.error {
display: none;
color: red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<label for="email">Positive</label>
<textarea type="email" class="form-control" id="email" oninput="someFunc()" placeholder="Tell people about your experience: describe the place or activity, recommendations for travelers?"></textarea>
<p id="max">Minimal length - symbols</p>
<div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (minimum:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long. Adding details really helps travelers.</span>
Hi everyone.I have a that simple textarea field.I need to realize something like that.When u write less than 100 words and click the outside of the email id the border color must be red.And error class must displayed.And i need to if the textarea field is empty the tag p with id max must be display block if the user will write any symbol the id max must bu display none.Thanks for help
function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
var integerValue = document.getElementById('email');
var hidden_block = document.querySelector('.hidden_block');
var max = document.getElementById('max');
var error = document.querySelector('.error');
var positive = document.getElementById("positive");
// var last2 = 100 - integer2;
if (integer >= 1) {
hidden_block.style.display = 'inline-block';
max.style.display = 'none';
integerValue.classList.add("form-control");
} else {
hidden_block.style.display = 'none';
max.style.display = 'block';
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
}
integerValue.addEventListener("click", function(){
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
});
//Red error and border
document.body.addEventListener("click", function(e) {
var target = e.target || e.srcElement;
if (target !== integerValue && !isChildOf(target, integerValue)) {
error.style.display = "inline-block";
integerValue.classList.add("form-redBorder");
positive.style.color = "red";
} if (integer >= 100) {
error.style.display = "none";
integerValue.classList.remove("form-redBorder");
positive.style.color = "#002C38";
}
}, false);
function isChildOf(child, parent) {
if (child.parentNode === parent) {
return true;
} else if (child.parentNode === null) {
return false;
} else {
return isChildOf(child.parentNode, parent);
}
}
//Finished Red error and border
//Start to count symbols
if (symbolCount >= 100) {
hidden_block.style.color = 'green';
}
else if (symbolCount <= 100) {
hidden_block.style.color = 'black';
}
else {
max.style.color = 'black';
// document.getElementById('max2').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
#email {
display: block;
padding: 6px 12px;
margin: 0 auto;
width: 90% !important;
height: 120px !important;
/*border:1px solid #44A1B7 !important;*/
}
.form-control {
margin: 0 auto;
width: 90% !important;
height: 120px !important;
border:1px solid #44A1B7;
}
#positive, #negative {
padding: 14px 15px 1px 55px;
color: #002C38;
font-size: 18px;
}
.form-redBorder {
margin: 0 auto;
border:1px solid #FF0000 !important;
}
#max, #max2 {
position: absolute;
right: 1%;
margin-right: 55px;
}
.hidden_block {
position: absolute;
right: 1%;
display: none;
text-align: right;
margin-right: 55px;
}
.error {
margin-left: 55px;
display: none;
color: #FF0000;
}
<form role="form">
<div class="form-group">
<p class="help-block">About youre site.</p>
<label for="email" id="positive">Positive</label>
<textarea type="email" id="email" oninput="someFunc()" placeholder="Your review must be at least 100 characters long<br> Adding details really helps travelers"></textarea>
<p id="max">(100 character minimum)</p><div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (min:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long.<br> Adding details really helps travelers..</span>
</div>
</form>

checkbox works only after second click after search

I'm trying to create list of suppliers (checkboxes + labels) and search field to filter suppliers. I managed to get list renderered and after first load it works fine, but after I search through supplier list first click on checkbox doesn't work. I need to click twice for checkbox to become checked.
screenshot
I need checkbox to become checked after first click when searching through supplier list. Please help.
I created this fiddle here
HTML:
<div class="col-sm-12">
<div class="infoBlock suppliersWrapper">
<div class="blockTitle">Supplier:</div>
<div class="blockContent">
<p class="checkedSupliersTitile">Supplier list:</p>
<div class="row">
<div class="col-sm-12 col-lg-8">
<input type="text" class="form-control stickTop" placeholder="Search..." id="SearchSupplierInput">
<ul class="supplierList scrollable" id="suppliers"></ul>
</div>
<div class="col-sm-12 col-lg-4">
<p class="checkedSupliersTitile">Checked suppliers:</p>
<p class="checkedSupliersText" id="checkedSuppliers">no suppliers selected</p>
</div>
</div>
</div>
</div>
</div>
CSS:
.supplierList label {
color: #575757;
display: block;
font-size: 15px;
font-weight: 400;
cursor:pointer;
font-family: 'Ubuntu', sans-serif;
}
.supplierList input[type="checkbox" ]{
width : 2em;
margin : 0;
padding : 0;
font-size : 1em;
opacity : 0;
}
.supplierList input[type="checkbox" ] + label{
display : inline-block;
margin-left : -1em;
line-height : 1.5em;
position:relative;
z-index: 33;
}
.supplierList input[type="checkbox"] + label::before {
border: 1px solid #d6d6d6;
border-radius: 1px;
content: "";
height: 20px;
left: -1.8em;
position: absolute;
top: 0.06em;
width: 20px;
-webkit-box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
-moz-box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
background: #ffffff;
}
.supplierList input[type="checkbox" ]:checked + label:before{
background:#46c87c;
}
.supplierList input[type="checkbox"]:checked + label::after {
color: #fff;
content: "";
font-family: "fontawesome";
left: -1.6em;
position: absolute;
top: 0;
}
JavaScript:
$(document).ready(function() {
var SupplierList = [{"name":"125","id":"1"},
{"name":"2Bit Telecom Corporation","id":"2"},
{"name":"Alleven Telecom Corp Standart","id":"3"}];
var selectedSuppliers = [];
// Собираем и фильтруем активных поставшиков
renderSupplierList(SupplierList);
$("#SearchSupplierInput").on("change paste keyup", function() {
var userInput = $(this).val();
var my_json = JSON.stringify(SupplierList);
var filtered_supplierList = find_in_object(JSON.parse(my_json), {name:userInput});
if (userInput.length >= 3) {
$("#suppliers").html("");
renderSupplierList(filtered_supplierList);
} else if(!userInput) {
$("#suppliers").html("");
renderSupplierList(SupplierList);
}
});
function renderSupplierList(array) {
array.forEach(function(item, i) {
if(typeof selectedSuppliers["id"+item.id] === 'undefined') {
var ifCheckd = "";
}
else {
var ifCheckd = "checked";
}
$("#suppliers").append('\
<li><span>\n\
<input class="supplierSelect" type="checkbox" id="supplier'+i+'" ' + ifCheckd + ' name="supplier" value="'+ item.id +'"> \n\
<label for="supplier'+i+'">'+ item.name +'</label>\n\
</span></li>');
});
}
function find_in_object(my_object, my_criteria) {
return my_object.filter(function(obj) {
//console.log(obj);
return Object.keys(my_criteria).every(function(c) {
//if (obj[c].search(/my_criteria[c]/i) == -1) {
if (obj[c].search(new RegExp(my_criteria[c], "i")) == -1) {
return false;
} else {
return true;
}
});
});
}
$('.supplierList').on('change', 'input[type=checkbox]', function() {
supplierCheckboxChange(this);
});
function sortSingle(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
function supplierCheckboxChange(currEl) {
var cText = $( currEl ).siblings("label").text();
var cID = "id" + currEl.value;
if(currEl.checked) {
selectedSuppliers[cID] = cText;
}
else {
delete selectedSuppliers[cID];
}
var tmpSuppl = [];
for (var key in selectedSuppliers) {
tmpSuppl.push(selectedSuppliers[key]);
}
tmpSuppl.sort(function(a, b) {
var x = a.toLowerCase(); var y = b.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
var suppliers = tmpSuppl.join(', ');
if (!suppliers) {
suppliers = "no suppliers selected";
}
$('#checkedSuppliers').text(suppliers);
}
});
This happens because your renderList function is being called more than once. First keyup is triggered when you press a key and then when text box looses focus(when you click on checkbox) change is triggered.
This causes your renderList method to get executed twice and the checked checkbox gets replace by a new checkbox.
To fix this, just change
$("#SearchSupplierInput").on("change paste keyup", function() { ... }
To
$("#SearchSupplierInput").on("paste keyup", function() { ... }
Have a look at this fiddle and check the console. https://jsfiddle.net/nh7u4Lck/2/

How can I search in the js array?

I'm trying to suggest the name of people when user inputs # in the textarea. Here is what I have done so far:
var Names = $('td').map(function() { return $(this).text(); }).get();
function SuggestPeople() {
var $textarea = $('.TxtArea');
var textarea = $textarea[0];
var sel = $textarea.getSelection();
var val = textarea.value;
var pos = sel.start;
if(val.substr(pos-1,1) == '#'){
for (var i = 0; i < Names.length; i++) {
Names[i] = "<span>" + Names[i] + "</span>";
}
$('.SuggestPeople').html(Names);
} else {
$('.SuggestPeople').html('');
}
}
$('.TxtArea').on('keydown click', function(e) {
// e.preventDefault();
SuggestPeople();
});
table{
display:none;
}
div{
background-color:#eee;
min-height: 20px;
width: 200px;
padding-top:5px;
margin-bottom: 3px;
}
div > span{
border: 1px solid gray;
margin: 0 3px;
}
textarea{
width: 195px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rangyinputs.googlecode.com/svn/trunk/rangyinputs_jquery.min.js"></script>
<table>
<tr>
<td>Jack</td>
<td>Peter</td>
<td>Barmar</td>
</tr>
</table>
<div class="SuggestPeople"></div>
<textarea class="TxtArea"></textarea>
In the code above, it suggests all names (which are exist in the array) to user. But actually I need to improve it and just suggest those names which are near to what user writes after #. How can I do that? I want exactly something like stackoverflow.
Here's a solution that should work for you:
// polyfills for older browsers
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
// code
var Names = $('td').map(function () {
return $(this).text();
}).get();
function SuggestPeople(e) {
var val = e.target.value,
suggest = document.getElementById('SuggestPeople');
if (val.substr(- 2).startsWith('#')) {
suggest.innerHTML = '<span>' + Names.map(function (v) {
var end = val.substr(- 1).toLowerCase();
if (v.startsWith(end) || v.startsWith(end.toUpperCase())) {
return v;
}
}).filter(function (v) {
return v
}).join('</span><span>') + '</span>'
} else {
suggest.innerHTML = '';
}
}
$('.TxtArea').on('keyup', function (e) {
// e.preventDefault();
SuggestPeople(e);
});
table{
display:none;
}
div{
background-color:#eee;
min-height: 20px;
width: 200px;
padding-top:5px;
margin-bottom: 3px;
}
div > span{
border: 1px solid gray;
margin: 0 3px;
}
textarea{
width: 195px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rangyinputs.googlecode.com/svn/trunk/rangyinputs_jquery.min.js"></script>
<table>
<tr>
<td>Jack</td>
<td>Peter</td>
<td>Barmar</td>
</tr>
</table>
<div id="SuggestPeople"></div>
<textarea class="TxtArea"></textarea>
Please note that String.prototype.startsWith() doesn't work in IE and older browsers, but you can find a polyfill here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

javascript background image change using array

I am not exprienced javascript programmer so I try to play with javascript. I am trying to make a slideshow by clicking on a button. Function I am trying to make a function with array that holds the names of all the images and changing the background-image according to the index of the array. I did only this part of function yet and I cant get what is wrong.
function change(lol){
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(change === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
}
middle {
width:1262px;
height:550px;
background-color: white;
margin-left: -7px;
}
#vvvmiddle {
width:700;
height:400;
background-image:url('veni1.jpg');
margin: 20px 0px 0px 310px;
float:left;
}
#sipka {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px 410px 0px 0px;
}
#sipkatext {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 10px;
padding-top: 1px;
}
#sipkaurl {
text-decoration: none;
}
#sipka:hover {
background-color: #3399FF;
}
#sipka2:hover {
background-color: #3399FF;
}
#sipka2 {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px -100px 0px 0px;
}
#sipkatext2 {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 13px;
padding-top: 1px;
}
<div id="middle">
<div id="vvvmiddle">
<div id="sipka" onclick="change('left')">
<div id="sipkatext">
<</div>
</div>
<div id="sipka2" onclick="change('right')">
<div id="sipkatext2">></div>
</div>
</div>
</div>
A possible solution may be this one:
var img = ["img1.png", "img2.png", "img3.png"];
var len = img.length;
var url = 'Some url...';
var current=0;
var middle = document.getElementById("vvvmiddle");
middle.style.backgroundImage = "url(" + url + img[current] + ")";
function change(dir){
if(dir == "right" && current < len-1){
current++;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
} else if(dir == "left" && current > 0){
current--;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
}
}
See it in action, check here jsfiddle.
You can try with that:
function change(lol) {
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(lol === "right"){
index = (index + 1) % img.length;
} else {
index = (index + img.length - 1) % img.length;
}
middle.style.backgroundImage = img[index];
}
You are checking wrong variable in condition, it should be lol, not change:
if(lol === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
Also you should handle "last image" case like Nicolas suggests.

Categories

Resources