Javascript image swap sequence - javascript

As a task i am going to make traffic lights change in sequence when a button is pushed.I am going to do this by using a variable and adding one to it each time a image is shown therefore the computer knows what image to display next through the use of if and elses however i am not great at javascript and it will not run i have tried in many different environments for example in dreamweaver and notepad ++ but am getting no where here is what i have got :
<HTML>
<head>
<title>Untitled Document</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap(a)">GO</button>
</body>
<script>
var a = 0
function imageswap(a)
{
if (var a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
var a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.png';
var a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.png';
var a==0;
}
}
</script>
</html>
Thank you for reading and i would appreciate anyones help.
edit:
I have taken on feedback and amended my code but when testing it does not show the image i would like instead the little x .
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0
function imageswap()
{
if (a=0) {
document.getElementById('IMAGE').src='red_empty_empty.gif';
a = a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.gif';
a = a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.gif';
var a=0;
}
}
</script>
</html>
edit:
I have taken into account some recommendations and now when i click the button the first image is shown followed by the second on a second button press however it fails to display the third image and the first and second image dont always work first time.
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0;
function imageswap() {
if (a == 0) {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a += 1;
} else if (a == 1) {
document.getElementById('IMAGE').src = 'empty_amber_empty.gif';
a += 1;
} else {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a = 0;
}
}
</script>

in you first line var a = 0 you declare your counter (the var a part) and initialise it by assigning the value 0 (the a = 0 part), therefore there's no need to declare the variable again later, you just want to update it by assigning new values
so the statement if (var a==0) would be incorrect syntactically, because you can't check if a variable declaration is 0. you can of course check if the previously declared variable has a value of 0, which would be if (a==0)
same goes when you try to increment the counter value. var a + 1; is wrong, because you can't increment by 1 a declaration. you should instead assign to the existing counter, the value of itself plus 1, so a = a + 1;
finally, when you try to reset the counter, var a==0;, (beside the usual declaration error) remember that == is comparison and = is assignment. You shouldn't check if the counter is 0, you should assign the value 0 to the counter to reset it.
hope it helps

I Apply with in console.log(a).It will show the increment of a\
Apply the var a in globel It will increment on each time of you click
And increment Apply with a +=1 instead of a+1
var a = 0
console.log(a)
function imageswap(){
if (a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
a += 1;
console.log(a)
} else if (a==1){
document.getElementById('IMAGE').src='empty_amber_empty.png';
a += 1;
console.log(a)
} else {
document.getElementById('IMAGE').src='empty_empty_red.png';
a =0;
console.log(a)
}
}
<button onclick="imageswap()">GO</button><br>
<img id="IMAGE" width="100" height="200"></img>

Ok Few things you need to take care:
You are passing a within the function imageswap(a) and you are accessing a from the value passed within the function that'll be 0 all the time. Check https://jsfiddle.net/aegwj88g/
You are checking var a==0, var a==1 which is incorrect. It should be like if(a==0) or else if(a==1).
You are trying to assig value to a with var a + 1 which is also incorrect. Left hand side must be a valid variable other than the javascript tokens (check JS naming convention) which stores the value. it should be a=a+1 (or a+=1) just as you do in maths;
Check this fiddle:

Related

Problems Cycling through Images with JavaScript

I am currently having a problem with my function not correctly cycling through images. The first image I have in the html code will show, but the code attempts to switch to a second image but instead just shows the blank white background. All images lie in the same directory folder. I have checked and made sure all file names and extensions match the their true names, attempted to find any syntax errors that might be causing this not to run but to no avail. could it be the fact that I am attempting to create an array and populate it at the same time, but doing so incorrectly?
Here is the answer I based my code off of: Link
Here's my current relevant code:
JS:
<script type="text/javascript">
function displayNextImage() {
var i = (i === imgArray.length - 1) ? 0 : i + 1;
document.getElementById("image").src = imageArr[i];
}
function displayPreviousImage() {
var i = (i <= 0) ? imgArray.length - 1 : i - 1;
document.getElementById("image").src = imageArr[i];
}
function startTimer() {
setInterval(displayNextImage, 2000);
}
var imageArr = ["~/Images/Carrying Food In.jpg", "~/Images/Food Pantry.jpg", "~/Images/Fresh Produce.jpg", "~/Images/Handing Out Food.jpg", "~/Images/Man Pushing Wheelbarrow.jpg", "~/Images/Woman Leading Class.jpg"], i = -1
</script>
Relevant HTML:
<body onload="startTimer()">
<img id="image" src="~/Images/Food Pantry.jpg" style="width: auto;" />
<p></p>
</body>
Edit: Changed one method to previous (had two of the same method names) - problem still persists
That's because of misspelled reference to your array and because on every function run you redeclare iterator variable var i. This code should work:
<script type="text/javascript">
var imageArr = ["~/Images/Carrying Food In.jpg", "~/Images/Food Pantry.jpg", "~/Images/Fresh Produce.jpg", "~/Images/Handing Out Food.jpg", "~/Images/Man Pushing Wheelbarrow.jpg", "~/Images/Woman Leading Class.jpg"], i = -1
var i;
function displayNextImage() {
i = (i <= 0) ? imageArr.length - 1 : i - 1;
document.getElementById("image").src = imageArr[i];
}
function startTimer() {
setInterval(displayNextImage, 2000);
}
</script>

The array won't work with the output of my pictures

I tried to show pictures with an array so I can change it per delay, kinda like a slideshow. The problem is, that only the first picture will load. when the counter of the array changes, the picture won't load.
The paths of the images are all correct
<!DOCTYPE html>`enter code here`
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test2</title>
<script>
var bilder = [];
var zeit = 3000;
var p = 0;
bilder[0] = "../Bilder/Bild1.jpg";
bilder[1] = "../Bilder/Bild2.jpg";
bilder[2] = "../Bilder/Bild3.jpg";
bilder[3] = "../Bilder/Bild4.jpg";
function BildAutoWeiter()
{
document.bild.src = bilder[p];
for( var i=0; i<= bilder.length; i++)
{
if(i <= bilder.length)
{
p++;
}
else
{
i = 0;
}
}
setTimeout("BildAutoWeiter()", zeit);
}
</script>
</head>
<body onload="BildAutoWeiter()">
<div>
<img name ="bild" width="100%" height="50%">
</div>
</body>
</html>
You need to use getElementsByName() to choose elements by their name=''. That returns an array of elements that use that name, so to choose a specific one, use an index [index] starting from 0. Do this instead:
document.getElementsByName('bild')[0].src = bilder[p];
That selects the first element that uses name='bild'
Also, the for statement is a bit useless. You could instead do:
function BildAutoWeiter()
{
document.bild.src = bilder[p];
p++;
setTimeout(BildAutoWeiter, zeit);
}
You don't need to put the function name in quotations and you can't have the parentheses while calling the function in setTimeout.

Re-using a variable not possible due to scoping issue. How can I fix this?

I expect to be able to use 'validBet' in a new function. The validBet is the basically the last value of the array 'betButtonsArr'. So the last clicked button will be the bet, not any of the previous. Now I need to be able to use the validBet to determine the bet placed, to calculate loss/winnings in a new function.
The problem is that I get a validBet is undefined error.
I am only using VanillaJS since I want to learn JS first before moving onto libraries.
// starter cash will be 100.
var cashTotal = 100; //Cash currently holding.
var showTotal = document.querySelector("#amount").innerHTML = cashTotal;
var bet = [5, 10, 50, 100]; //Bets you can do.
var numGenerated;
function updateDisplay() {
document.querySelector('#generated_number').innerHTML = "".split.call(numGenerated, "").join("");
}
function highLow(){
var storeNum = Math.floor(Math.random() * 11) + 0;
numGenerated = storeNum;
}
function choiceLow(){
highLow();
updateDisplay();
console.log(numGenerated);
if (numGenerated < 5){
// run function to add winnings
}
else {
// run function to subtract bet amount.
return;
}
}
function choiceHigh(){
highLow();
updateDisplay();
console.log(numGenerated);
if (numGenerated == 5 || numGenerated > 5){
// run function to add winnings.
}
else {
// run function to subtract bet amount.
return;
}
}
var betAmount = [];
function placeBet(){
var betBtn_nodelist = document.querySelectorAll('.bet_amount > button');
var betButtonsArr = Array.prototype.slice.call(betBtn_nodelist);
//
for (var i = 0; i < betButtonsArr.length; i++) {
betButtonsArr[i].onclick = function(){ // when clicked, push value of clicked button to betAmount array for grabbing the placed bet.
betAmount.push(this.value);
console.log(betAmount);
var validBet = betAmount[betAmount.length - 1]; // when multiple bet amounts are clicked, take the last amount chosen, make that the final and valid bet amount.
console.log(validBet) //This is the real bet amount, as explained one line above.
console.log(cashTotal)
}
}
}
placeBet();
function addWinningsAmount(){
}
function subtractBetAmount(){
}
var lower = document.querySelector("#lower");
var higher = document.querySelector("#higher");
lower.addEventListener('click', choiceLow);
higher.addEventListener('click', choiceHigh);
HTML code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Betting Project</title>
<link rel="stylesheet" href="betting.css">
</head>
<body>
<div class="cash_total"><p>Your balance is: <span id="amount"></span>.</p></div>
<h1 style="text-align: center;">BET NOW</h1>
<div class="bet_amount">
<button class="five" value="5">5</button>
<button class="ten" value="10">10</button>
<button class="fifty" value="50">50</button>
<button class="hundred" value="100">100</button>
</div>
<div id="generated_number"></div>
<div class="buttonHolder" style="text-align: center;">
<button id="lower">LOWER</button>
<button id="higher">HIGHER</button>
</div>
<script src="betting.js"></script>
</body>
</html>
I expect to use this and grab the value of the bet. Instead of that, I get the ReferenceError: validBet is not defined. I'm guessing this is a scoping problem, but I have no idea how to best sort this out.
function addWinningsAmount(){
console.log(validBet)
}
when declaring global objects in javascript, you need to declare it at the top. Any variable declared inside a function is limited to that function only.
or else, if the variable still needs to be declared inside the function but with global scope, use window declaration. For eg. window.validBet = betAmount[betAmount.length - 1];. Make sure the function declaring the variable is called before the function accessing the variable.
do not use 'var' while declaring global variables.

JavaScript Countdown with argument passing in

You are given an integer called start_num. Write a code that will countdown from start_num to 1, and when the countdown is finished, will print out "Liftoff!".
I am unsure how to do this and keep getting stuck.
This is the code I am provided with at the beginning of the problem:
function liftoff_countdown(start_num) {
// My code goes here!
}
And then they want me to pass in a value such as the 5:
liftoff_countdown(5);
And then this will be my output:
6
5
4
3
2
1
"Liftoff!"
Thanks!
Look at this maybe help you to create your own code
make two file in a same folder (script.js and index.html)
index.html
<!doctype html>
<head>
<title>Countdown</title>
</head>
<body>
<div id="container">
<div id="inputArea">
</div>
<h1 id="time">0</h1>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
var valueRemaining;
var intervalHandle;
function resetPage() {
document.getElementById("inputArea").style.display = "block";
}
function tick() {
var valueDisplay = document.getElementById("time");
valueDisplay.innerHTML = valueRemaining;
if (valueRemaining === 0) {
valueDisplay.innerHTML = "Liftoff!";
clearInterval(intervalHandle);
resetPage();
}
valueRemaining--;
}
function startCountdown() {
var count = document.getElementById("count").value;
if (isNaN(count)) {
alert("Please enter a number!");
return;
}
valueRemaining = count;
intervalHandle = setInterval(tick, 1000);
document.getElementById("inputArea").style.display = "none";
}
// as soon as the page is loaded...
window.onload = function () {
var inputValue = document.createElement("input");
inputValue.setAttribute("id", "count");
inputValue.setAttribute("type", "text");
// create a button
var startButton = document.createElement("input");
startButton.setAttribute("type", "button");
startButton.setAttribute("value", "Start Countdown");
startButton.onclick = function () {
startCountdown();
};
// add to the DOM, to the div called "inputArea"
document.getElementById("inputArea").appendChild(inputValue);
document.getElementById("inputArea").appendChild(startButton);
};
in this example you have many things to understand how javascript works behind scenes.
How about this...
function liftoff_countdown()
{
var span=document.getElementById('num');
var i=document.getElementById('num').innerText;
i=i-1;
span.innerText=i;
if (i==0){
span.innerText='Liftoff!';
clearInterval(count_down)
}
}
var count_down=setInterval(liftoff_countdown,1000);
<span id="num">5</span>
You can achieve this with a simple recursive function and the use of setTimeout to recursively call the function after a time lapse of 1 second.
function lift_off(seconds) {
if(seconds == 0) {
console.log('liftoff');
} else {
console.log(seconds--);
setTimeout(function(){lift_off(seconds);},1000);
}
}
lift_off(10);
Here is a working JSFiddle
Preface
A lot of these answers seem to be focused on doing things with timers and recursion. I do not believe that is your intent. If your only goal is to print those values to the console, you could simply do the following (see the comments for an explanation).
The Answer
function liftoff_countdown(start_num) {
// Loops through all values between 0 and start_num
for(int i = 0; i < start_num; i++) {
// Prints the appropriate value by subtracting from start_num
console.log( start_num - i );
}
// Upon exiting the loop, prints "Liftoff!"
console.log("Liftoff!");
}
Additional Thoughts
You could just as easily loop backwards through the numbers instead of forward like so:
for(int i = start_num; i > 0; i--){
console.log( i );
}
I tend to lean towards iterating forwards just because it's more common, and it's often easy to confuse readers of your code if they gloss over the loop initialization.
Additionally, I am working with the assumption that when you say "print" you mean "console.log()". If this is untrue, you could of course use any other function in its place (e.g. alert( "Liftoff!" );).

I can't get my image slideshow to work using JavaScript

I am trying to create a simple image slideshow type thing with the Javascript code below, but what it is doing is displaying the first image in the webpage with everything else, then after 5 seconds clearing the page and displaying the same image, then again every 5 seconds except it doesn't clear the page anymore.
The JavaScript:
var waiPics=new Array();
waiPics[0]='images/path.jpg';
waiPics[1]='images/gorse.jpg';
waiPics[2]='images/stream.jpg';
waiPics[3]='images/pines.jpg';
waiPics[4]='images/stump.jpg';
var time;
function timeUp() {
delete document.write();
nextPic();
}
function nextPic() {
var picNum=0;
if (picNum = waiPics.length) {
picNum=0;
}
else {
picNum++;
}
document.write('<img src="'+waiPics[picNum]+'" title="Waipahihi" alt="Waipahihi">');
time=setTimeout("timeUp()",5000);
}
The HTML:
<script type="text/javascript">
<!-- Begin
nextPic();
// End -->
</script>
Im not very experienced with Javascript, so thanks in advance for the help.
picNum will always be zero because it is declared inside a function and will set to zero every time the function is called. Even if you fix this, your condition is wrong:
if (picNum = waiPics.length) {
The conditional should be:
if (picNum === waiPics.length) {
The single = sign assigns the length to picNum, then converts to a boolean. The array length is nonzero, so it becomes true value. It then resets to zero every time.
Consider using JSLint to check your code for errors and to suggest improvements. It flagged the issue:
"Expected a conditional expression and instead saw an assignment."
if (picNum = waiPics.length) {
In fact, after using JSLint on your code and examining its suggestions, I would use something more like this:
// New array creation syntax
var waiPics = ['images/path.jpg', 'images/gorse.jpg', 'images/stream.jpg', 'images/pines.jpg', 'images/stump.jpg'];
var picNum = 0; // Declare outside inner function so its value is preserved
var myDiv = document.getElementById("ssdiv"); // Get a div element to insert picture into
function nextPic() {
if (picNum === waiPics.length) { // Proper comparison
picNum = 0;
} else {
picNum += 1;
}
// Set picture into div element without evil document.write
myDiv.innerHTML = '<img src="' + waiPics[picNum] + '" title="Waipahihi" alt="Waipahihi">';
// No longer need timeUp; also don't use eval syntax
setTimeout(nextPic, 5000);
}
Assigning innerHTML avoids various problems with document.write and also does not require your page to refresh to change slideshow images. Also note other comments.
You need to use the comparison operator ('==') instead of assigning ('=') here:
//if (picNum = waiPics.length) {
if (picNum == waiPics.length) {
have a look at this example...
http://jsfiddle.net/DaveAlger/eNxuJ/1/
to get your own slideshow working, copy and paste the following html into any text file and save it as slides.html
you can add any number of <img> elements inside the <div class="slideshow">
enjoy!
<html>
<body>
<div class="slideshow">
<img src="http://davealger.info/i/1.jpg" />
<img src="http://davealger.info/i/2.bmp" />
<img src="http://davealger.info/i/3.png" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function(){
$('.slideshow img:gt(0)').hide();
setInterval(function(){$('.slideshow :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('.slideshow');}, 4000);
});
</script>
<style>
.slideshow { position:relative; }
.slideshow img { position:absolute; left:0; top:0; }
</style>
</body>
</html>

Categories

Resources