button to start and stop my code in javascript - javascript

I would like to have a stop and start button for my code. So I can break the working the source code does.
<script language="JavaScript">
var i = 0;
var path = new Array();
// LIST OF IMAGES
path[0] = "http://static.giantbomb.com/uploads/original/0/31/11738-ssj_goku.jpg";
path[1] = "http://i.kinja-img.com/gawker-media/image/upload/arjw8wqvwnihalb6fq3k.png";
path[2] = "http://orig03.deviantart.net/8999/f/2013/167/1/7/sword_art_online_by_sakimichan-d69cxwk.jpg";
function swapImage() {
document.slide.src = path[i];
if (i < path.length - 1)
i++;
else
i = 0;
setTimeout("swapImage()",3000);
}
window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />

This will define a variable (running) and toggle between true and false on click of the toggle link:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var running = true;
var i = 0;
var path = new Array();
// LIST OF IMAGES
path[0] = "http://static.giantbomb.com/uploads/original/0/31/11738-ssj_goku.jpg";
path[1] = "http://i.kinja-img.com/gawker-media/image/upload/arjw8wqvwnihalb6fq3k.png";
path[2] = "http://orig03.deviantart.net/8999/f/2013/167/1/7/sword_art_online_by_sakimichan-d69cxwk.jpg";
function ToggleRunning()
{
running = !running;
if (running)
swapImage();
}
function swapImage()
{
document.slide.src = path[i];
if(i < path.length - 1) i++; else i = 0;
if (running)
setTimeout("swapImage()",3000);
}
window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
<button onclick="ToggleRunning();">Toggle</button>
</body>
</html>

Related

How to delete the text and print new text letter by letter by clicking once after printing a text letter by letter

I'm quite a newcomer to HTML Front End, and now working on the school project to make a simple text interactive game, but I'm now stuck by this problem when I'm trying to make the interface better.
I can now implement this function by clicking the text button once to clearout the former text and clicking twice to print new text, but I want to realize these two effects at the same time by only clicking once.
I want to fix this problem by optimizing the function replace(),but it doesn't seem to work ,since the new text I want to print simply appear for about 50ms and disappear but I don't really know why.It seems to be something wrong with the function setInterval(),
Is there any possible ways to optimize it?
(the following is the code)
<html>
<head>
<meta charset="utf-8">
<title>Part1-intro2</title>
<link href="../css/main.css" rel="stylesheet" type="text/css"/>
<script src="../js/jquery-1.11.1.min.js"></script>
<script src="../js/Main.js"></script>
<script>
window.onload=function()
{
var temp = document.getElementsByClassName('dialog')[0];
var text = 'test text1';/*这里改对话内容*/
var len = text.length;
var timer = null;
var index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML+=text.charAt(index++);
},125);
}
function goForward()
{
window.location.assign("Sc2.html");
}
var t=0;
function replace()
{ if(t==0)
{
var temp = document.getElementsByClassName('dialog')[0];
var text = '';/*这里改对话内容*/
var len = text.length;
var timer = null;
var index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML=text.charAt(index);
},10);
t++;
}
else if(t==1)
{
temp = document.getElementsByClassName('dialog')[0];
text1 = 'test text1';
len = text1.length;
timer = null;
index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML+=text1.charAt(index++);
},50);
t++;
}
else if(t==2)
{
var temp = document.getElementsByClassName('dialog')[0];
var text = '';/*这里改对话内容*/
var len = text.length;
var timer = null;
var index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML=text.charAt(index);
},10);
t++;
}
else if(t==3)
{
var temp = document.getElementsByClassName('dialog')[0];
var text1 = 'test text2';/*这里改对话内容*/
var len = text1.length;
var timer = null;
var index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML=text1.charAt(index++);
},50);
t++;
}
else if(t==4)
{
goForward();
}
}
</script>
<style>
body {
background: url(../images/bg_通学路2.png) no-repeat;
background-size:100% 100%;;
}
</style>
</head>
<body background="../images/bg_通学路2.png">
<div>
<button class="basbt" id="ico-home" onclick="toHome()"></button>
<button class="basbt" id="ico-back" onclick="Back()"></button>
<button class="basbt" id="ico-save" onclick="Savegame()"></button>
</div>
<div class="Text" onclick="replace()">
<span class="cover1"></span>
<div class="dialog"></div>
<div class="Guide">>></div>
</div>
</body>
</html>

How to remove the uploaded image in any box?

My code is very long. I can not show you all here. I just show the javascript code only
My javascript like this :
<script type="text/javascript">
let current = 0;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-delete-'+i).click(function(){
current -= 1;
$('input[name="photo-'+i+'"]').val('');
document.getElementById("thumbnail-view-li-"+current).style.display = "none";
document.getElementById("thumbnail-upload-li-"+current).style.display = "";
document.getElementById("thumbnail-upload-li-"+(current+1)).style.display = "none";
document.getElementById("thumbnail-slot-li-"+(current+1)).style.display = "";
});
}
var editClicked = false;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-edit-'+i).click(function(){
editClicked = true;
$('input[name="photo-'+i+'"]').click();
});
}
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-add-'+i).click(function(){
editClicked = false;
$('input[name="photo-'+i+'"]').click();
});
}
for(let i = 0; i < 5; i++) {
var reader = new FileReader();
$('input[name="photo-'+i+'"]').change(function (e) {
let indexPhoto = i;
current += 1;
reader.onload = function(){
imageProducIsLoaded(indexPhoto);
};
reader.readAsDataURL(e.target.files[0]);
});
}
function imageProducIsLoaded(indexPhoto) {
$('#thumbnail-view-'+indexPhoto).attr('src', reader.result);
if (!editClicked) {
document.getElementById("thumbnail-upload-li-"+indexPhoto).style.display = "none";
document.getElementById("thumbnail-view-li-"+indexPhoto).style.display = "";
if((indexPhoto+1) < 5) {
document.getElementById("thumbnail-upload-li-"+(indexPhoto+1)).style.display = "";
document.getElementById("thumbnail-slot-li-"+(indexPhoto+1)).style.display = "none";
}
}
};
</script>
You can see my complete code and demo here : http://www.phpfiddle.org/main/code/adjv-sfuy
I use show hide to add, delete and edit image. If you look at the demo, it has worked. Images can be edited, deleted and added
But my problem is when the user does delete image
When user delete an image, the image on last box is deleted. Should be when user delete an image, then the image that I click its delete button is deleted
For example I input 5 image. When deleting image to 3, image to 3 deleted
I've been trying to modify the code for some days, but I have not found a solution
Is there anyone who can help me?
Use jquery features for doing complex things very simple.
<?php
if(isset($_POST['submit'])) {
echo "<pre>";
print_r($_FILES);
for($i=0;$i<count($_FILES);$i++) {
if($_FILES['photo-'.$i]['error'] == 0) {
$file_name = $_FILES['photo-'.$i]['name'];
$file_tmp =$_FILES['photo-'.$i]['tmp_name'];
move_uploaded_file($file_tmp,"img/".$file_name);
}
}
echo "</pre>";
}
?>
<style type="text/css">
.img-container{width:162px;height:142px;border:1px dashed #337ab7;float:left;margin-right:5px;position:relative;border-radius:5px}
.upload-add-product{position:absolute;display:block;margin:34% 42%}
.upload-add-product i{font-size:30px}
.img-container ul{list-style:none;bottom:0;position:absolute;width:100%;padding:0;margin:0;background-color:rgba(255,255,255,0.7)}
.img-container ul li{display:inline;padding:0;display:table-cell;width:1%;text-align:center;position:relative;padding:2px 0}
.img-container ul li:hover{background-color:#eee}
.img-container ul li a{color:red}
</style>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form method="post" enctype="multipart/form-data">
<div class="images-area">
<?php
for($i=0;$i<5; $i++) { ?>
<div class="img-container" id="box<?php echo $i ?>" data-status="0" data-index="<?=$i?>">
<input type='file' name="photo-<?=$i?>" style="visibility: hidden;position:absolute;" id="upload-file<?=$i?>" class="upload-file"/>
<div class="image">
<?php if ($i == 0): ?>
<i class="fa fa-plus"></i>
<?php endif; ?>
</div>
</div>
<?php } ?>
</div>
<input type="submit" name="submit" value="submit">
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on('change',".upload-file",function () {
var $input = $(this);
var inputFiles = this.files;
if(inputFiles == undefined || inputFiles.length == 0) return;
var inputFile = inputFiles[0];
var i = parseInt($(this).closest('.img-container').attr('data-index'));
var reader = new FileReader();
reader.onload = function(event) {
// console.log($('#box'+i).find('img').length);
if($('#box'+i).find('img').length) {
$('#box'+i).find('img').attr('src',event.target.result);
} else {
var imgTmpl ='<img height="142" width="162" src='+event.target.result+'>'+
'<ul><li class="btn-click" onclick=\'$("#upload-file'+i+'").click()\'><i class="fa fa-pencil"></i></li>'+
'<li class="delete-button"><i class="fa fa-trash"></i></li></ul>';
$('#box'+i+' .image').html('');
$('#box'+i+' .image').append(imgTmpl);
$('#box'+i).attr('data-status',1);
$('#box'+(i+1)+' .image').html('</i>');
}
};
reader.onerror = function(event) {
alert("I AM ERROR: " + event.target.error.code);
};
reader.readAsDataURL(inputFile);
});
$(document).on('click','.delete-button',function(){
var i = $(this).closest('.img-container').attr('data-index');
$('#box'+i).remove();
$('.images-area').append('<div class="img-container" data-status="0"><input type="file" style="display:none" id="upload-file" class="upload-file"><div class="image"></div></div>');
var blank = 0;
$('.img-container').each(function(i){
$(this).attr({'id':'box'+i,'data-index':i});
$(this).find('.upload-file').attr({'id':'upload-file'+i,'name':'photo-'+i});
$(this).find('.btn-click').attr('onclick','$("#upload-file'+i+'").click()');
if(($(this).attr('data-status') == 0) && (blank == 0)) {
blank = i;
}
});
if($('.img-container').find('.upload-add-product').length == 0) {
$('#box'+blank+' .image').append('</i>');
}
});
</script>
I put efforts for understand your task..
See this it will help you..
Sorry, I was misunderstand.
Mayby you need a judgement after you delete an image that make sure the next image is not show.
$('#thumbnail-view-delete-'+i).click(function(){
$('input[name="photo-'+i+'"]').val('');
document.getElementById("thumbnail-view-li-"+i).style.display = "none";
document.getElementById("thumbnail-upload-li-"+i).style.display = "";
if(document.getElementById("thumbnail-view-li-"+(i+1)).style.display === "none"){
document.getElementById("thumbnail-upload-li-"+(i+1)).style.display = "none";
document.getElementById("thumbnail-slot-li-"+(i+1)).style.display = "";
}
});
This can descrease the messy.
I have found out your problem. Your delete function does not detect the number of photos currently uploaded but simply deletes the last one.
Added: current photo count, changed delete method to use current instead of 'i', increment count on upload and decrement count on delete.
<script type="text/javascript">
let current = 0;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-delete-'+i).click(function(){
current -= 1;
$('input[name="photo-'+i+'"]').val('');
document.getElementById("thumbnail-view-li-"+current).style.display = "none";
document.getElementById("thumbnail-upload-li-"+current).style.display = "";
document.getElementById("thumbnail-upload-li-"+(current+1)).style.display = "none";
document.getElementById("thumbnail-slot-li-"+(current+1)).style.display = "";
});
}
var editClicked = false;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-edit-'+i).click(function(){
editClicked = true;
$('input[name="photo-'+i+'"]').click();
});
}
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-add-'+i).click(function(){
editClicked = false;
$('input[name="photo-'+i+'"]').click();
});
}
for(let i = 0; i < 5; i++) {
var reader = new FileReader();
$('input[name="photo-'+i+'"]').change(function (e) {
let indexPhoto = i;
current += 1;
reader.onload = function(){
imageProducIsLoaded(indexPhoto);
};
reader.readAsDataURL(e.target.files[0]);
});
}
function imageProducIsLoaded(indexPhoto) {
$('#thumbnail-view-'+indexPhoto).attr('src', reader.result);
if (!editClicked) {
document.getElementById("thumbnail-upload-li-"+indexPhoto).style.display = "none";
document.getElementById("thumbnail-view-li-"+indexPhoto).style.display = "";
if((indexPhoto+1) < 5) {
document.getElementById("thumbnail-upload-li-"+(indexPhoto+1)).style.display = "";
document.getElementById("thumbnail-slot-li-"+(indexPhoto+1)).style.display = "none";
}
}
};
</script>
Here's my answer: http://phpfiddle.org/main/code/0h1g-mvus
I just shift the images instead. You might need to do some changes to pass values or w/e.
let current = 0;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-delete-'+i).click(function(){
current -= 1;
$('input[name="photo-'+i+'"]').val('');
document.getElementById("thumbnail-view-li-"+current).style.display = "none";
document.getElementById("thumbnail-upload-li-"+current).style.display = "";
document.getElementById("thumbnail-upload-li-"+(current+1)).style.display = "none";
document.getElementById("thumbnail-slot-li-"+(current+1)).style.display = "";
shift_image(i);
});
}
function shift_image(start)
{
let finish = 4;
for (; start < finish - 1; start++)
{
let next = $('#thumbnail-view-'+(start+1)).attr('src');
$('#thumbnail-view-'+start).attr('src', next);
}
}

How To Change Image in Array Based on Textbox input in JavaScript?

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

Input Button onclick event not firing

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);
};

Second picture sliding is not working by javascript

I want to add two picture slider at same page by JavaScript only. But only one slider is working and another is static.
Here is my code so far what I got from a website.
<script type="text/javascript">
window.onload = function() {
var rotator = document.getElementById("rotator");
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function() {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 3000);
};​
</script>
<div id="rotator">
<img height="250px" width="200px" src="images/claim/1.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/2.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/3.jpg" alt="" />
</div>
Its because your code is applying the slide function only on one div.
Create another div with id = 'rotator2', then the following code will trigger slide on both.
<script type="text/javascript">
window.onload = function() { slideIt("rotator");slideIt("rotator2") ; } ;
function slideIt(contId) {
var rotator = document.getElementById(contId);
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 3000);
};
</script>
You'll have to define two <div> for example rotator1 and rotator2, and apply the JS code to the 2 blocks.
<script type="text/javascript">
window.onload = function () {
var rotator = document.getElementById("rotator1");
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 3000);
};
</script>
<div id="rotator1">
<img height="250px" width="200px" src="images/claim/1.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/2.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/3.jpg" alt="" />
</div>
<script type="text/javascript">
window.onload = function () {
var rotator = document.getElementById("rotator2");
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 3000);
};
</script>
<div id="rotator2">
<img height="250px" width="200px" src="images/claim/3.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/4.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/5.jpg" alt="" />
</div>
Note that you should better define a JS function in a separate file and call it two times

Categories