what is wrong with my code. javascript slideshow - javascript

HTML:
<div id='container'>
<img id= 'img' src='images/pic1.jpg' name='slideshow'/>
<button onclick='slide(-1)'>previous</button>
<button onclick='slide(1)'>next</button>
</div>
Try to make a JavaScript slideshow but the code doesn't work. What is wrong with my code?
JavaScript:
var i = 0;
var path = new Array();
path[0] = "images/pic1.jpg";
path[1] = "images/pic2.jpg";
path[2] = "images/pic3.jpg";
function slide(v) {
var x = x + v;
if(i < path.length){
i = i - x;
}
if(i > path.length){
x = path.length;
}
document.slideshow.src = path[i];

Try this:
<html>
<head>
<script type="text/javascript">
<!--
var image1=new Image()
image1.src="1.jpg"
var image2=new Image()
image2.src="2.jpg"
var image3=new Image()
image3.src="3.jpg"
//-->
</script>
</head>
<body>
<img src="1.jpg" name="slide" width="500" height="250" />
<script>
<!--
//variable that will increment through the images
var step=1
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.images.slide.src=eval("image"+step+".src")
if (step<3)
step++
else
step=1
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}
slideit()
//-->
</script>
</body>

you need to check the value if i if you can still increment or decrement
var path = new Array();
path[0] = "https://www.mavericklabel.com/images/products/preprinted-stock/stock-label/color-coded/rectangle/rectangle-green-3x5-inch-200x200.png";
path[1] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSLNrcoSk41WfHji3m9JPbgWkdgPPstVtWfDLLUtcnEGloFwDNT";
path[2] = "http://www.dots-by-inlingua.com/img/intro/dot_7.png";
var x;
var i = 0;
function slide(v) {
if (v === -1) {
if (i !== 0) i = i + v;
}
if (v === 1) {
if (i < path.length -1) i = i + v;
}
document.slideshow.src = path[i];
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='container'>
<img id= 'img' src='https://www.mavericklabel.com/images/products/preprinted-stock/stock-label/color-coded/rectangle/rectangle-green-3x5-inch-200x200.png' name='slideshow'/>
<button onclick='slide(-1)'>previous</button>
<button onclick='slide(1)'>next</button>
</div>

Related

Images not showing up in Javascript

This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');

How can I display four images randomly with link and without duplicates using Javascript?

I'm trying to display four images randomly with a related link, by avoiding to display duplicated images each time. I've found how to randomly display a random image with the link, but I have no idea how to create the loop part and how to check for duplicates. I would appreciate your help.
<script>
function random_imglink(){
var myimages=new Array()
myimages[1]="image1.gif"
myimages[2]="image2.gif"
myimages[3]="image3.gif"
myimages[4]="image4.gif"
myimages[5]="image5.gif"
myimages[6]="image6.gif"
var imagelinks=new Array()
imagelinks[1]="http://www.page1.com"
imagelinks[2]="http://www.page2.com"
imagelinks[3]="http://www.page3.com"
imagelinks[4]="http://www.page4.com"
imagelinks[5]="http://www.page5.com"
imagelinks[6]="http://www.page6.com"
var ry=Math.floor(Math.random()*myimages.length);
if (ry==0)
ry=1;
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>');
}
random_imglink()
</script>
Thanks in advance :)
As stated on this answer, you can create a method for checking of duplicates.
method:
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
usage:
var imagelinks= [0,1,2],
index = contains.call(imagelinks, imagelinks[ry]); //boolean
Outside of your function, declare an array to hold elements that are already displayed:
var displayed = [];
Then after your if (ry==0) condition add this:
if (displayed.indexOf(ry) !== -1){
displayed.push(ry);
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>');
} else {
random_imglink();
}
You should learn about Constructors. When you call new on them they return an Object which has separate properties based on the Constructor. Below is some code that will help you along your journey.
//<![CDATA[
// external.js
var doc, bod, htm, C, E, inArray, ShuffleMagic; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
inArray = function(needle, haystack){
for(var i=0,l=haystack.length; i<l; i++){
if(haystack[i] === needle){
return true;
}
}
return false;
}
function ShuffleMagic(haystack){
var a;
this.haystack = haystack;
this.alterOriginal = false;
this.shuffle = function(limit){
var r, s = this.haystack;
if(!a){
a = [].slice.call(s), l = a.length;
for(var i=0,n=1,f,h; i<l; i++,n++){
f = Math.floor(Math.random()*n); h = a[i]; a[i] = a[f]; a[f] = h;
}
}
if(limit){
if(a.length >= limit){
r = a.splice(0, limit);
if(a.length < limit)a = undefined;
}
else{
a = undefined;
return this.shuffle(s.length);
}
}
else{
r = a; a = undefined;
}
if(this.alterOriginal){
s.splice.apply(s, [0, s.length].concat(r)); a = undefined;
}
return r;
}
}
var imagelinks = ['http://www.page1.com', 'http://www.page2.com', 'http://www.page3.com', 'http://www.page4.com', 'http://www.page5.com', 'http://www.page6.com', 'http://www.page7.com', 'http://www.page8.com', 'http://www.page9.com',
'http://www.page10.com', 'http://www.page11.com', 'http://www.page12.com', 'http://www.page13.com', 'http://www.page14.com', 'http://www.page15.com', 'http://www.page16.com', 'http://www.page17.com', 'http://www.page18.com', 'http://www.page19.com'];
var max = E('limit'), out = E('out');
var wow = new ShuffleMagic(imagelinks);
// wow.alterOriginal = true;
// wow.haystack = ['Replace', 'other', 'array, 'example'];
E('testButton').addEventListener('click', function(){
out.innerHTML = wow.shuffle(+max.value).join('<br />');
});
});
//]]>
/* external.css */
html,body{
margin:0; padding:0;
}
.main{
width:980px; margin:0 auto;
}
#limit{
width:30px; padding-left:3px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Shuffle Magic</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='test.js'></script>
</head>
<body>
<div class='main'>
<label for='limit'>Limit:</label><input id='limit' name='limit' type='text' value='4' /><input id='testButton' type='button' value='Click Me' />
<div id='out'></div>
</div>
</body>
</html>
With this version, which is recursive (probably beyond your understanding right now), the array elements only recycle once they've been completely or nearly completely gone through. Enjoy!

Need Assistance With JavaScript ImageSlider - What Am I Doing Wrong?

<script type="text/javascript">
var imageCounter = 1;
Function change() {
var image = doc.getElementById("image2");
if( imageCounter==1 ) {
image.src = '2.jpg';
imageNumber = 2;
}
else if( imageCounter==2 {
image.src = '3.jpg';
imageNumber = 3;
} else {
imageCounter = 1;
}
setInterval("change()",6500);
<button id="knapp1" type="button" onclick="change()">==></button>
Can anyone tell me what I am doing wrong? I have been trying to understand what I'm failing.
The main problem is that sometimes you assign to imageCounter and sometimes you assign to imageNumber. Decide on one name and use it consistently.
Also, function does not start with a capital letter. JavaScript is case-sensitive.
One problem is that you have
Function change()
with a capital F.
It should be function change()
another thing is that imageNumber is not declared. Im not sure what it is or what its used for but just do
var imageNumber;
setInterval("function()",6000);
It should not be in quotes.
setInterval(change(),6000);
Next thing, is that if you are running this off your computer, it will not find 3.jpg
Instead you have to give the complete file location of the image.
One last thing: on your function you are missing a curly bracket at the end.
heii
copy this code
<html>
<head>
<link rel="stylesheet" type="text/css" href="boss.css">
<script language="JavaScript">
var i = 0;
var path = new Array();
// LIST OF IMAGES
path[0] = "1.jpg";
path[1] = "2.jpg";
path[2] = "3.jpg";
function change()
{
document.slide.src = path[i];
if(i < path.length - 1) i++; else i = 0;
setTimeout("swapImage()",6500);
}
window.onload=change;
</script>
</head>
<body>
<center>
<img src="1.jpg" border="1" name="slide" height="300" width="750" id="image2"/>
</center>
<button id="knapp1" type="button" onclick="change()">==></button>
</body>
</html>

Need help creating a button to activate a javascript function

This is my script, I am trying to make a button randomize the images instead of me having to press the refresh button. What exactly do I need to code the button as to make this work?
My code
I think I am confused on what my function name is? I had a lot of help creating this so I'm a bit lost on what to do as far as the button is. I've created a button and I've tried plugging in multiple things for the "onclick" but nothing works.
<!doctype html>
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
var theImages = new Array()
theImages[0] = '<img class="atvi-image-image" alt=""src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png" title="" height="467" width="675">'
theImages[1] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png" title="" height="732" width="1084">'
theImages[2] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-extra-slots.png" title="" height="480" width="752">'
theImages[3] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-2025.png" title="" height="412" width="683">'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
(function () {
var theImages = [{
src: "winry doe.gif",
width: "480",
height: "270"
}, {
src: "WINRY WINK.gif",
width: "500",
height: "484"
}, {
src: "winry getting hugged.gif",
width: "500",
height: "205"
},
{
src: "winry getting mad.gif",
width: "500",
height: "292"
}];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.getRandomImage = function () {
var whichImage = getRandomInt(0, preBuffer.length - 1);
return preBuffer[whichImage];
}
})();
window.onload = function () {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
</script>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
<form>
<input type="button" value="More Winry" onclick="">
</form>
</body>
</html>
Just add :
function randomImage() {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
and to the button onclick add:
<input type="button" value="More Winry" onclick="randomImage()">
EDIT
To replace existing image:
function randomImage() {
var newImage = getRandomImage();
console.log(newImage);
var img = document.getElementsByTagName('img').remove();
document.body.appendChild(newImage);
};
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
add those function instead.
Credits to JavaScript: remove element by id
also, no need of JQuery in functions so JQuery tag is useless.
You can also use similar to this (as long as the img's have that class). Using the prototype method described by Edan Feiles answer
the button html:
<form>
<input id="imageButton" type="button" value="More Winry" />
</form>
and the JS:
var button = document.getElementById("imageButton");
button.onclick = function() {
var newImage = getRandomImage();
console.log(newImage);
document.getElementsByClassName("atvi-image-image").remove();
document.body.appendChild(newImage);
};
or you can use what Edan Feiles said and just add this line to the function:
document.getElementsByClassName("atvi-image-image").remove();
before adding the new random image.

Javascript code not running well on IE9

I have code which is supposed to display an ad for 10 seconds, then load a embed code.
It is working fine on Firefox, but on IE9 it runs the ad and the embed code in the same time in the background.
<script type="text/javascript">
var nbsec = 10;
var c = 0;
var t;
var timer_is_on = 0;
var sum = 0;
function timedCount()
{
c = c + 1;
t = setTimeout("timedCount()", 1000);
sum = nbsec - c;
document.getElementById('chrono').innerHTML = "<br>Loading .. Please wait " + sum + "secondes";
if(c == nbsec) {
stopCount();
document.getElementById('mypub').style.visibility = 'hidden';
document.getElementById('mygame').style.visibility = 'visible';
document.getElementById('mygame').style.display = 'block';
document.getElementById('mygame').style.height = 'auto';
document.getElementById('mypub').style.height = '0px';
document.getElementById('mypub').style.padding = '0px';
document.getElementById('mypub').innerHTML = "";
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on = 0;
}
</script>
<table border="2" align="center" color="F2FC7E">
<tr>
<td>
<div id="mypub" style="visibility: visible; text-align:center; padding:20px;">
<script>
..............
</script>
<div id="chrono" style="color:#FFF;"></div>
</div>
<div id="mygame" style="visibility: hidden;display:none; height:0px">
<param name="initial_focus" value="true">
<applet>
........................
</applet>
</div>
</td>
</tr>
</table>
<script type="text/javascript">
timedCount();
</script>
Is there is anyway to resolve this problem?
<script type="text/javascript">
var nbsec = 10;
function timedCount() {
document.getElementById('chrono').innerHTML = "<br>Loading .. Please wait " + nbsec + "secondes";
if( nbsec ){ // if sum != 0, wait call again
setTimeout( timedCount, 1000 );
nbsec--; // counter
} else { // do after 10 sec
document.getElementById('mygame').style.cssText = "visibility:visible;display:block;height:auto;";
document.getElementById('mypub').style.cssText="visibility:hidden;height:0px;padding:0px;";
document.getElementById('mypub').innerHTML = "";
}
}
// stopCount is not needed
// start counter
timedCount();
</script>
that`s about logic

Categories