I'm fairly new to JavaScript and trying to build a simple photoviewer, slideshow application. I probably have errors/wrong practices in code that I don't know about yet. The event on slideshow button fires and I can see the output in the console, however the event on the random slide show button does not fire.
HTML5 snippet
<form>
<div id="controls">
<input type="button" id="slideshow" value="Slide Show" />
<input type="button" id="randomSlideshow" value="Random Slide Show" />
</div>
</form>
<script src="js/PhotoViewer.js"></script>
</body>
JS snippet
var photosArrayGlobal = new Array();
var photoIndexGlobal = 0;
var displayGlobal;
window.onload = main;
function main() {
"use strict";
document.getElementById("slideshow").onclick = getArrayPhotosNames;
document.getElementById("randomSlideshow").onclick = randomize(photosArrayGlobal);
displayGlobal = document.getElementById("myImage");
document.getElementById("nextSlide").onclick = function () {
displayGlobal.setAttribute("src", photosArrayGlobal[1]); //Test value, image 2
};
}
function getArrayPhotosNames() {
var folderName = document.getElementById("photoFolder").value;
var commonName = document.getElementById("commonName").value;
var startNum = document.getElementById("startNum").value;
var endNum = document.getElementById("endNum").value;
var j = 0;
if (startNum > endNum) {
alert("Invalid Numbers");
}
var nameArray = new Array();
for (var i = startNum; i <= endNum; i++) {
nameArray[j] = folderName + commonName + i + ".jpg";
j++;
}
photosArrayGlobal = nameArray.slice();
console.log(photosArrayGlobal);
return nameArray;
}
function randomize(dataArray) {
var i = dataArray.length;
var j, tempi, tempj;
if (i === 0) {
return false;
}
while (--i) {
j = Math.floor(Math.random() * (i + 1));
tempi = dataArray[i];
tempj = dataArray[j];
dataArray[i] = tempj;
dataArray[j] = tempi;
}
console.log(dataArray);
}
The onclick handler is expecting a function, but you're passing it the value returned from the randomize() function (which happens to be undefined). Change it to the following:
document.getElementById("randomSlideshow").onclick = function() {
randomize(photosArrayGlobal);
};
Related
I would love some help with this project. I am creating a small project with Javascript, I am still new with HTML,CSS, and JavaScript. What I would like to do with my program, is that the counter will stop after 1 minute has passed and a pop up window appears that no more clicks are accepted. Below is my code, any help will be appreciated!!
var count = 0;
var countblack = 0;
var countred = 0;
var countButton = document.getElementById("black");
var countButtonC = document.getElementById("red");
var displayCount = document.getElementById("displayCount");
black.onclick = function() {
count++;
countblack++;
displayCount.innerHTML = count;
displayCountblack.innerHTML = countblack;
}
red.onclick = function() {
count++;
countred++;
displayCount.innerHTML = count;
displayCountred.innerHTML = countred;
}
http://jsfiddle.net/wr1ua0db/544/
You can use setTimeout to count 60seconds and then disable the buttons. Below is the solution
var allowClick = true;
var count = 0;
var countblack = 0;
var countred = 0;
var black = document.getElementById("black");
var red = document.getElementById("red");
var displayCount = document.getElementById("displayCount");
var displayBlackCount = document.getElementById("displayBlackCount");
var displayRedCount = document.getElementById("displayRedCount");
black.onclick = function() {
if (!allowClick) return;
count++;
countblack++;
displayCount.innerHTML = count;
displayBlackCount.innerHTML = countblack;
}
red.onclick = function() {
if (!allowClick) return;
count++;
countred++;
displayCount.innerHTML = count;
displayRedCount.innerHTML = countred;
}
startTime(60); // time in seconds
function startTime(time) {
var timer = setTimeout(function() {
black.setAttribute('disabled', 'disabled');
red.setAttribute('disabled', 'disabled');
allowClick = false;
clearTimeout(timer)
}, 1000 * time)
}
<button id="black">Count Black</button>
<button id="red">Count Red</button>
<div>Display Count: <span id="displayCount">0</span></div>
<div>Black Count: <span id="displayBlackCount">0</span></div>
<div>Red Count: <span id="displayRedCount">0</span></div>
when I call this function "showMe(calcTotal(myNumberArray));" in the console it works, but it doesn't work when called in the code. Sorry if my code herts you eyes or doesn't make since. it's supposed to calculate the total. I would like to know why the browser doesn't see the invocation or why the value is not displayed on the screen.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
</style>
</head>
<body>
<button id="hit">hit</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
<script>
//Services helper functon
var myNumberArray = [];
document.getElementById('hit').onclick = function randomNumber() {
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML=card;
myNumberArray.push(card);
var number =myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
};
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for(var i = 0; i < myNumberArray.length; i++){
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
what = calcTotal(myNumberArray);
var what= calcTotal(myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
}
showMe(calcTotal(myNumberArray));
</script>
</body>
</html>
If you want to update the total value on click of the button, then you need to call showMe(calcTotal(myNumberArray)); inside the click handler.
//Services helper functon
var myNumberArray = [];
document.getElementById('hit').onclick = function randomNumber() {
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML = card;
myNumberArray.push(card);
var number = myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
showMe(calcTotal(myNumberArray));
};
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for (var i = 0; i < myNumberArray.length; i++) {
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
what = calcTotal(myNumberArray);
var what = calcTotal(myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
}
showMe(calcTotal(myNumberArray));
<button id="hit">hit</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
I'm trying to make my page so a user can type a number value between 1 and 200 to get to whichever image they want to view. I've played around with the code, but I can't seem to get anything to work. Below is my code that I've tried to do this with. What am I doing wrong?
Edit: New Code:
`
<html>
<head>
<title></title>
</head>
<body style="background-color: teal;">
<form>
<center>
<div width="50%" style="width: 50%;">
<div id="main" align="middle">
<img src="page1.jpg" alt="" id="mainImg" height="90%">
</div>
<div id="imglist">
<a href="javascript:previousImage('mainImg')"><img src="previous.png" alt=""
align="left"></a>
<input id="myid" name="myid" size="3" type="text"></input>
<img src="next.png" alt="" align="right">
<script>
var imgArray = new Array();
var imgs = [];
for (var i = 0; i < 200; i++) {
imgs[i] = new Image();
imgs[i].src = "page" + (i + 1) + ".jpg";
}
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
function previousImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src)
{
if(i === 0){
document.getElementById(element).src = imgArray[imgArray.length-1].src;
break;
}
else{
document.getElementById(element).src = imgArray[i-1].src;
break;
}
}
}
}
window.onload = function() {
var elm = document.getElementById("myid"),
var img = document.getElementById("mainImg");
elm.onkeyup = function(event) {
if (this.value) {
var num = parseInt(this.value, 10);
if (num >= 1 && num <= 200 {
img.src = "page" + num + ".jpg";
}
}
}
}
</script>
</div>
</div>
</center>
</form>
</body>
</html>
Perhaps you mean for this:
if (this.value.length === 1,2,3) {
to be this:
if (this.value.length <= 3) {
In addition, I think you want to be converting the whole input value to a number, not using the individual keycodes.
I might suggest this different/simpler way of doing this that is much more DRY (don't repeat yourself):
// preload images
var imgs = [];
for (var i = 0; i < 200; i++) {
imgs[i] = new Image();
imgs[i].src = "page" + (i + 1) + ".jpg";
}
window.onload = function() {
var elm = document.getElementById("myid");
var img = document.getElementById("mainImg");
elm.onkeyup = function(event) {
if (this.value) {
var num = parseInt(this.value, 10);
if (num >= 1 && num <= 200) {
img.src = "page" + num + ".jpg";
}
}
}
}
Working Demo: http://jsfiddle.net/jfriend00/4dqbP/
Summary of changes:
Preload images in a loop rather than copied code
Construct image names dynamically
Make img variable to a local variable rather than an implicit global with var in front of it
Check to see if the input field is empty
Use parseInt() to parse the value of the input field into a number
Range check the parsed number
If in valid range, then construct the image name using that number
I used the below code to upload multiple files. Its working absolutely fine but as i need to check that the file which i am uploading is duplicate or not, i am facing one problem in that. I created one function called checkDuplicate for that and calling it inside the function. But the problem is that the for loop is looping double the size of the array. I don't know why it is so. Please kindly help me if anyone has any idea.
Here is the Javascript
<script type="text/javascript">
function MultiSelector(list_target, max) {
this.list_target = list_target;
this.count = 0;
this.id = 0;
if (max) {
this.max = max;
} else {
this.max = -1;
};
this.addElement = function(element) {
if (element.tagName == 'INPUT' && element.type == 'file') {
element.name = 'file_' + this.id++;
element.multi_selector = this;
element.onchange = function() {
var new_element = document.createElement('input');
new_element.type = 'file';
this.parentNode.insertBefore(new_element, this);
this.multi_selector.addElement(new_element);
this.multi_selector.addListRow(this);
this.style.position = 'absolute';
this.style.left = '-1000px';
};
if (this.max != -1 && this.count >= this.max) {
element.disabled = true;
}
;
this.count++;
this.current_element = element;
}
else {
alert('Error: not a file input element');
}
;
};
this.addListRow = function(element) {
var new_row = document.createElement('div');
var new_row_button = document.createElement('img');
new_row_button.setAttribute("src","<%=request.getContextPath()%>/images/deletei.gif");
new_row_button.onclick = function() {
this.parentNode.element.parentNode.removeChild(this.parentNode.element);
this.parentNode.parentNode.removeChild(this.parentNode);
this.parentNode.element.multi_selector.count--;
this.parentNode.element.multi_selector.current_element.disabled = false;
return false;
};
if(checkDuplicate(element)) {
new_row.element = element;
new_row.innerHTML = element.value + " ";
new_row.appendChild(new_row_button);
this.list_target.appendChild(new_row);
}
};
};
function checkDuplicate(element) {
var arr = new Array();
var i = 0,dup=0;
//alert(new_row.element = element.value);
if(dup==0) {
arr[i++] = element.value;
dup=1;
}
alert("Length ==> "+ arr.length);
for ( var j = 0; j < arr.length; j++) {
alert("Name ==> " + arr[j]);
if(arr[j] == element.value && j>=1) {
alert("Duplicate");
} else {
alert("Not Duplicate");
arr[i++] = element.value;
}
}
}
</script>
Here is the HTML
<body>
<!-- This is the form -->
<form enctype="multipart/form-data" action=""method="post">
<input id="my_file_element" type="file" name="file_1">
<input type="submit">
<br/>
<br/>
Files:
<!-- This is where the output will appear -->
<div id="files_list"></div>
</form>
<script>
var multi_selector = new MultiSelector(document
.getElementById('files_list'), 15);
multi_selector.addElement(document.getElementById('my_file_element'));
</script>
</body>
</html>
because you have the arr[i++] = element.value; in the last line, and j < arr.length in the for, so every time the array.lenght gets bigger and bigger.
change the for line to these two lines:
var len = arr.length;
for ( var j = 0; j < len; j++) {
Im trying to get the index number of corresponding characters in a string.
I mean a loop does make it possible to treat characters in a string like an 'array' of characters with the string method charAt() and indexOf(), right?
here's the code:
/** ****** WINDOW ONLOAD EVENT HANDLER **************** */
window.onload = function(){
// DOM elements
var theButton = document.getElementById('theButton');
var form = document.formISBN;
var numberField = document.getElementById('theInput')
theButton.onclick = function(){
var number = numberField.value;
console.log(number)
controlNr = calculControlNr(number);
// console.log(controlNr);
}
}
function calculControlNr(number) {
number = number.replace(' ','','g');
number = number.replace('-','','g');
var sum = 0;
var sumEven = 0;
var sumUneven = 0;
var factor = 3;
var numberExtract = number.substr(0,11);
console.log(numberExtract.length)
for (var i = 0; i < numberExtract.length; i++) {
console.log(numberExtract.indexOf(numberExtract.charAt(i)));
}
}
How about
var numberExtract = number.split('');
console.log(numberExtract.length)
for (var i = 0; i < numberExtract.length; i++) {
if (i==11) break; // you only wanted the first 11?
console.log(i+':'+numberExtract[i]);
}
But your code does work anyway.
Here is what I did to test it
<script>
/** ****** WINDOW ONLOAD EVENT HANDLER **************** */
window.onload = function(){
// DOM elements
var theButton = document.getElementById('theButton');
var form = document.formISBN;
var numberField = document.getElementById('theInput')
theButton.onclick = function(){
var number = numberField.value;
alert(number)
controlNr = calculControlNr(number);
// alert(controlNr);
}
}
function calculControlNr(number) {
number = number.replace(' ','','g');
number = number.replace('-','','g');
var sum = 0;
var sumEven = 0;
var sumUneven = 0;
var factor = 3;
var numberExtract = number.substr(0,11);
alert(numberExtract.length+':'+numberExtract);
for (var i = 0; i < numberExtract.length; i++) {
alert(i+':'+numberExtract.indexOf(numberExtract.charAt(i)));
}
}
</script>
<form name="formISBN">
<input id="theInput" type="text" value="01234567890-A A" />
<input id="theButton" type="button" value="click"/>
</form>