I’m really new to JavaScript and trying to figure out a basic slide with pictures built in an array. Like you click next and previous to get new images.
How can I do that? Here is what I have so far.
<html>
<body>
<script>
imgArray = new Array(
“image”,
“image”
“image”);
x=1
y=2;
function move{
y = y+xflip;
if (y>x)
{y = 1;}
if (y==0)
{y = x;
document.images[2].src = img[y-1];}
</script>
<input type=“button” value=“Prev” name=“buttonp” onclick=“slide(-1)”>
<input type=“button” value=“Next” name=buttonb” onclock=“slide(1)”>
<img src=“image1”>
</body>
</html>
Please help. Thanks.
I like the jquery approach.
You could try something like this. You would need to add a bit extra logic for clicking previous at first go etc.
<button id=“buttonprev” type="button">Previous</button>
<button id=buttonforward”>Next</button>
<img id="preview" src="#" alt="your image" />
<script>
var imgArray = ['image1.png', 'image2.png', 'image3.png'];
var imgCount = 0;
$("#buttonforward").on('click', function(event) {
imgCount += 1;
$('#preview').attr('src', imgArray[imgCount]);
});
$("#buttonprev").on('click', function(event) {
imgCount -= 1;
$('#preview').attr('src', imgArray[imgCount]);
});
</script>
Related
I'm working on a project for a friend and he wants a pure walk cycle with only HTML/JS (no CSS). So I've tried to work it out but the image only shows up on the webpage.
It doesn't move when I press any buttons or anything at all.
Please show me where I went wrong. I'm used to using HTML and CSS but this is my first JS so I don't know many terms.
How it appears in the website:
My code (HTML + JS):
<!DOCTYPE html>
<html>
<head>
<title>Javascript Animation</title>
<script language="Javascript">
<!--
var walker = new Array(6);
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5) curWalker == 0;
else ++curWalker;
document.animation.src = walker[curWalker].src;
}
-->
</script>
</head>
<body>
<p><img src="walk1.png" name="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval('marathon(),100);">
<input type="button" name="stop" value="stop" onclick="clearsetInterval(startwalking);">
</form>
</body>
</html>
Here it is how I did it get to work (I had to build my simple images with Paint in order to use them in the animation):
<html>
<head>
<title>Javascript Animation</title>
</head>
<body>
<p><img src="walker1.png" id="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval(marathon,100);">
<input type="button" name="stop" value="stop" onclick="clearInterval(startWalking);">
</form>
<script>
var walker = [];
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5)
curWalker = 0;
else
++curWalker;
document.getElementById("animation").src = walker[curWalker].src;
}
</script>
</body>
</html>
I had to correct several typos/mistakes:
Put the JS just before the </body> closing tag
The first paramether of setInterval() must be a function name, so it must be marathon (you had 'marathon(); note that leading single quote)
In order to get the image to be substituted it is better to access the element though Id instead of name attribute. So I changed the image to <img src="walker1.png" id="animation"> (animation is now the Id) and accessed it through document.getElementById("animation")
Now the animation starts... but stops to the last image instead of restarting to the first.
That was because you used to check the curWalker variable instead of performing an assignment: I put curWalker = 0; instead of curWalker == 0;
Almost there. The loop is complete, but the stop button doesn't work. Two typos are preventing this to work:
clearsetInterval doesn't exist. The function to be called is clearInterval
Javascript is a case sensitive language. You use startwalking variable as a parameter, but the correct variable name is startWalking. So you have to correct the onclick event writing clearInterval(startWalking); instead of clearsetInterval(startwalking);
Your animation is now complete.
Note: as correctly noted by #Mike 'Pomax' Kamermans, nowadays you can avoid the use of onclick as you can attach events to the document (such as "click") by using document.addEventListener.
<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image);
var desc = document.getElementById(desc);
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiD.jpg"]
var descs = ["1", "2"]
var num = 0;
var total = images.length;
function clicked(){
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById(submit).onclick(clicked());
</script>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
</html>
The line "document.getElementById(submit).onclick(clicked());" throws an error
"ReferenceError: submit is not defined"
When I tried accessing buttons in general
[through getElementsByClassName & getElementsByTagName]
it gave an error of "ReferenceError: button is not defined"
Using strings in getElementById it throws the error "getElementById is null"
I found several questions and answers to this.
Only one of them I understood how to implement, due to the use of PHP and that being the error on most others. Other solutions I found involved errors numerically.
On this error I tried a fix of printwindow.document.getElementById(..etc
This gives me an error of "ReferenceError: printwindow is not defined"
Browsers run JavaScript as soon as possible in order to speed up rendering. So when you receive this code:
<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image); // Missing quotes, typo?
... in runs intermediately. There's no <foo id="image"> on page yet, so you get null. Finally, you get the rest of the page rendered, including:
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
It's too late for your code, which finished running long ago.
You need to bind a window.onload even handler and run your code when the DOM is ready (or move all JavaScript to page bottom, after the picture).
It should be document.getElementById('submit').onclick(clicked());
your must enclose the id you are searching for in quotes:
document.getElementById('ID_to_look_up');
You are executing javascript before your 'body' rendered. Thus document.getElementById("submit") would return null. Because there are no "submit" DOM element yet.
One solution is to move your javascripts under 'body', Or use JQuery with
$(document).ready(function() {
...
});
Your variable also has scope problem, your function cannot access variable declared outside this function with 'var' declaration. If you really need that variable, you should remove 'var' declaration.
A better way is to move all your variable inside clicked function. like following code
<html>
<head>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
<script type="text/javascript">
function clicked(){
var image = document.getElementById("image");
var desc = document.getElementById("desc");
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiE.jpg"];
var descs = ["1", "2"];
var num = 0;
var total = images.length;
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById("submit").onclick = clicked;
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
var trafficlights = ['redlight.png','yellowlight.png','greenlight.png'];
var num = 1
function lightsequence() {
document.getElementById('light').src = trafficlights[num];
num = num + 1;
}
</script>
</head>
<body>
<img id="light" src="redlight.png">
<button onclick="lightsequence()">Change Lights</button>
</body>
</html>
I have written that piece of code and the images change in order one by one each time I click the button but I cannot think of how to reverse the order if I keep clicking, i.e. traffic lights red yellow green yellow red etc. each time I click. I am unfamiliar with jQuery so would like to not use them ideally but if someone can explain it fully with jQuery in working it will have to do.
Modulo operator is very convenient in such cases:
document.getElementById('light').src = trafficlights[num++ % trafficlights.length];
Here is a demo:
var trafficlights = [
'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png',
'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Yellow.png',
'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Green.png'
];
var num = 1
function lightsequence() {
document.getElementById('light').src = trafficlights[num++ % trafficlights.length];
}
<img id="light" src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png">
<button onclick="lightsequence()">Change Lights</button>
Change Lights
function lightsequence(){
document.getElementById("light").src
if(document.getElementById("light").src=="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png"){
document.getElementById("light").src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Yellow.png"
}else if(document.getElementById("light").src=="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Yellow.png"){
document.getElementById("light").src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Green.png"
}else{
document.getElementById("light").src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png"
}
}
<img id="light" src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png">
<button onclick="lightsequence()">Change Lights</button>
when I run this code it initially cant find the source "src="colour[var x]" " but once I have used colourChange it works fine, I just need to fix this one issue. any help would be much appreciated.
much thanks
src=[var x]
Javascript variables are not available in html elements attributes src="colour[var x]". So you have to initialize src with valid path value, or you can initialize it in js
...
var colour = ["red.gif", "amber1.gif", "green.gif", "amber1.gif"];
document.getElementById("light").src = colour[0];
function colourChange(){
...
Like this
<!DOCTYPE html>
<html>
<head>
<title>Traffic Lights</title>
</head>
<body>
<img id="light" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSeIlyurWoqEAMds0DmsxrFDr0R3bXCErkDAWGEnuUF757qN7uW" width="150px" height="150px">
<button onclick="colourChange()">Click Me To Cycle Through The Colours</button>
<script>
var x=0;
var colour = ["https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSeIlyurWoqEAMds0DmsxrFDr0R3bXCErkDAWGEnuUF757qN7uW", "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQ7t30uQ_C4eV-HXMFZU2EPlqQ_MwsMA2kEfkzBFjC3Sav4OM3n", "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSNxgGXA3G2NwGVo70gZmy3ccYEcOSo4vzcPsgQRLbU_hGIBCWrnA", "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSqFHvDm74NYMdbBtW-ZO9o3irXu4GHynOkDiCxDXJ484m1Ahyt"];
function colourChange(){
x += 1;
document.getElementById("light").src = colour[x];
if (x == 3) x = 0;
}
</script>
</body>
</html>
I am trying to pace two images in screen with their two separate counters above them. As well i am trying to make it modular and use a function which does initialization for onClick methods on the two images. However things does work out the way i expect. The two counters point to same memory location and clicking on any image retrieves the value from same counter.
How can i fix it and yet maintain the modularity?
.
<!DOCTYPE html>
<html>
<body>
<p id="text1"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image1">
<p id="text2"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image2">
<script>
function Counter(idText,idImage){
var that = this;
that.counter = 0;
document.getElementById(idImage).onclick = function(){
document.getElementById(idText).innerHTML = (++that.counter);
};
}
var image1 = Counter("text1","image1");
var image2 = Counter("text2","image2");
</script>
</body>
</html>
In your current code Counter("text1","image1"); will simply called that function, and its execution context will be window, so both of the image will use that window.counter as their counter.
So you need to add new to before Counter, which now will take Counter as a constructor, create a new object and then execute the code in Counter, while the this will be point to that newly created object. So both object will have their value independently.
In this case, the image1 will be object, which has an attribute counter, so you can use image1.counter to access the counter value in other place.
<!DOCTYPE html>
<html>
<body>
<p id="text1"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image1">
<p id="text2"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image2">
<script>
function Counter(idText,idImage){
var that = this;
that.counter = 0;
document.getElementById(idImage).onclick = function(){
document.getElementById(idText).innerHTML = (++that.counter);
};
}
var image1 = new Counter("text1","image1");
var image2 = new Counter("text2","image2");
</script>
</body>
</html>
Another way use var counter = 0; instead of this.counter = 0. Then when each of the image added a counter by the function, its click event handler will only see the counter declared in Couter. This is the Closures way.
In this case, the var image1 = Counter("text1","image1");, the var image1 is not necessary, you can just use Counter("text1","image1");, but if you still want some control over it, you can return somthing in Counter to control it. In this way, the user is only allowed to alter/see the values by functions you provided.
<!DOCTYPE html>
<html>
<body>
<p id="text1"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image1">
<p id="text2"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image2">
<script>
function Counter(idText,idImage){
var counter = 0;
document.getElementById(idImage).onclick = function(){
// Now each image's handler will see the counter we just defined,
// And not get messed with other images that also call the `Counter` function.
document.getElementById(idText).innerHTML = (++counter);
};
var setZero = function() {
counter = 0;
document.getElementById(idText).innerHTML = 0;
};
var shoutCount = function() {
alert('You clicked on' + idImage+ ' ' + counter + 'times.');
};
return {
setZero: setZero,
shoutCount: shoutCount
};
}
// If we want to have some control to image1 , but don't care other.
// Get the control's return by Counter call
var image1 = Counter("text1","image1");
// We don't want to control image2, simply call is ok.
Counter("text2","image2");
setTimeout(function() {
image1.shoutCount();
image1.setZero();
}, 3000);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="text1"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image1">
<p id="text2"></p>
<img src="http://www.w3schools.com/images/colorpicker.gif" id="image2">
<script>
function getImage(idText,idImage){
var newImage = new Object();
newImage.counter = 0;
newImage.onClick = function(){
document.getElementById(idText).innerHTML = (++newImage.counter);
};
document.getElementById(idImage).onclick = newImage.onClick;
}
getImage("text1","image1");
getImage("text2","image2");
</script>
</body>
</html>