I am trying to create code that goes through a traffic light sequence when I click the button. I know there are a lot of people having the same problem however none of the solutions they got seem to work - I can only get the first asset (red traffic light) to display on the webpage and when I click the button nothing happens... Maybe I just need my code proof reading and there is something really obvious I've made a mistake on?
Here is my code:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Task 3</h1>
<img id="image" src="red.png" style="width:200px">
<input type="button" onclick="nextpic()" value="change image" >
<script>
var image = document.getElementById("image");
var counter = 0;
var trafficlights = [
"redamber.png",
"amber.png",
"green.png",
"red.png"
];
function nextpic(){
counter =counter+1;
if (counter == trafficlights.length){
counter = 0;
}
image.src = trafficlights[counter];
}
</script>
</body>
</html>
Related
I want to create a basic page in html that displays a single image.
I also added two buttons Previous and Next. These buttons should allow the user to move forward or backward. Have 6 images in total. When the user reaches the end (or beginning when clicking on the back button) of the slide show, the slide show should not wrap around to the beginning (or end).
button onclick function for both the cases is not working. Its only getting displayed the first image as what mentioned in the img src attribute.
This is what I have done so far. I put all the images into an array and try to travel the array forward and backward side based on the button click.
<body>
<img src="img1.jpg" id="demo" style="width:400px;height:600px"/img>
<br/>
<input type="button" onclick="preImage()" value="Previous
">
<input type="button" onclick = "nextImage()" value="Next
">
<script>
var slider_content = document.getElementById("demo");
var image = ['img1','img2','img3','img4','img5','img6'];
var i = image.length;
function nextImage(){
if(i<image.length){
i=i+1;
}else{
i=1;
}
slider_content.innerHTML="<img src="+image[i-1]+".jpg>";
}
function preImage(){
if(i<image.length+1 && i>1){
i=i-1;
}else{
i=image.length;
}
slide_content.innerHTML = "<img src="+image[i-1]+".jpg">
}
</script>
</body>
Create a wrapper div to your image and change the innerHTML of the div.
<div id="demo" style="width:400px;height:600px">
<img src="img1.jpg">
</div>
An error needs to be corrected in the preImage function:
slide_content.innerHTML = "<img src="+image[i-1]+".jpg">
to
slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";
and also what Daniel said.
<html>
<head>
<title>How To Insert an Image</title>
<script>
function changeImage(){
var img = document.getElementById('image');
image.src='image4.jpg';
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
I am quite new to Javascript so please dont be too harsh. Basically im trying to switch from one picture to another using a button. So far with this code i have only managed to do 2 images but when i try to add a 3rd or 4th the first image messess up. I was hoping if someone could help me fix this problem.
Here's simplest approach the I used before, for two images. Easily extended to accomodate three, four, or more alternate images.
<div id="image1">
<img ... >
<button ...>
</div>
<div id="image2" style="display: none">
<img ... >
<button ...>
</div>
That is, put the first image, and a button, inside a "< div >" element, and a second image, and a button inside a second "< div >" element that's initially hidden.
Then, each button's javascript simply needs to set its own div's CSS style to "display: none", and remove this style from the other div element, effectively hiding one image, and displaying the other one.
This approach also makes it possible to update the button's text or label, accordingly. If both buttons have the same label, the only apparent result is the image change.
Try this script block instead:
<script>
var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg']
function changeImage() {
var img = document.getElementById( 'image' )
var url = images.shift() // remove first url from list
image.src = url // use it
images.push( url ) // append url to the end of the list
}
</script>
What you could do is declare an array which contains all your image urls:
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
Then when clicking the button, you remove the first image url from the the array by using shift and assign that to variable imageUrl.
Then you set that imageUrl to the src attribute of the image element on your page.
Then you add that imageUrl at the end of the array using push.
This will rotate the images in the imageUrls array on every click.
<html>
<head>
<title>How To Insert an Image</title>
<script>
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
function changeImage(){
var img = document.getElementById('image');
var imageUrl = imageUrls.shift();
img.src = imageUrl;
imageUrls.push(imageUrl);
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
You were very close! You just made mistake to assign a value to image.src instead of img.src. have a look at the code below :)
Using clicks:
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}
</script>
</head>
<body>
<img id="image" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" height="100px" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
Automatic image slider
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
setInterval(function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}, 5000)
</script>
</head>
<body>
<img id="image" src="image1.jpg" height="100px" />
</body>
</html>
Sorry if this is a silly question, but I've been trying to use AJAX to display my javascript variables in 'real time' with little luck. I'm definitely a beginner though so this could be the problem haha- When I see the AJAX code, it always seems to require an additional url that it refreshes, but I just want to refresh the javascript variables on click.
http://jsfiddle.net/bagelpirate/m9Pm2/
<script>
var one = 0;
var two = 0;
var three = 0;
</script>
<body>
<div id="div_1">
One: <script>document.write(one)</script> |
Two: <script>document.write(two)</script> |
Three: <script>document.write(three)</script>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" onclick="one++;" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" onclick="two++;" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" onclick="three++;" />
</div>
</body>
As you can see in the above code, when a user clicks one of the images, I want to increment the count and display it at the top of the page. I found the HTML5 output tag, and was wondering if it's possible to use this to display the javascript variable in real time? Everything I've read seems to imply it can't be done because the output tag only works on forms? Anyway, I figured it couldn't hurt to ask!
Thanks for your time!
You shouldn't use document.write to write to the DOM after it's finished loading. You have tagged your question with jQuery, so I'll assume you can use that to update things. Instead, update the DOM from within your script block. Here is an example that might help you get started.
http://jsfiddle.net/prxBb/
<script type="text/javascript">
$(function() {
var one = 0;
var two = 0;
var three = 0;
$('img#mine').click(function() {
one++;
$('span#one').html(one);
});
$('img#forest').click(function() {
two++;
$('span#two').html(two);
});
$('img#farm').click(function() {
three++;
$('span#three').html(three);
});
});
</script>
<body>
<div id="div_1">
One: <span id="one"></span> |
Two: <span id="two"></span> |
Three: <span id="three"></span>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" />
</div>
</body>
Maybe you should try putting all your variables inside a named object, iterating through it at predefined interval and displaying the values.
var varContainer = {
one:0,
two:0,
three:0
};
jQuery("#div_2 img").on('click',function(){
jQuery.each(varContainer,function(key,value){
//Add key + value to the DOM
if(jQuery("."+key+value).length<1)
jQuery("#div_2").append("<div class='"+key+value+"'></div>");
var newHtmlVal= "<p><span>Var name: "+key+"</span><br><span>Value: "+value+"</span>";
jQuery("."+key+value).html();
});
});
HTML
<div id="div_2">
</div>
Of course the script could be upgraded to look through each variable recursivley in case of nested objects/arrays...
Hope this helps!
I am new to this site and this is first question I am asking here..if its simple pls forgive me..
I have drawn one background image, on this I am drawing 5 small small images by using drawImage() method. Once I touch the small images then they should disappear or should pop up one alert box but ontouch event is not occurring so far I have searched for ontouch event but no use. I dont want to draw images through img tag in HTML.
Here is my code segment
var car = new Image();
car.src = "img/car.jpg";
car.onload = function() {
imgLoaded = true;
}
if (imgLoaded = true) {
drawBackgroundImg();
drawCarImg();
}
function drawCarImg() {
if (i == 0) {
x1 = Math.floor((Math.random() * 501));
y1 = Math.floor((Math.random() * 301));
cxt.save();
cxt.drawImage(car, x1, y1, car.width, car.height);
cxt.restore();
}
}
car.on('touchstart', function() {
alert("T");
});
Here is my HTML code
<!DOCTYPE html>
<body>
<div id="container" onclick="void(0)">
<canvas id="can"> </canvas>
</div>
<div id="btn">
<input type="image" id="zoomIn" src="img/up.png" onclick="zoomIn()" />
<input type="image" id="zoomOut" src="img/down.png"
onclick="zoomOut()" />
</div>
<div id="score">
<p id="scoreCount">
<b></b>
</p>
</div>
</body>
</html>
Could anybody help me to get the solution.
FYI: I am running this code in Phonegap NOT in browser.
$( '#id' ).on( 'touchstart',function(){
//your code
});
here id is id of your html element on which you want to listen touch event.
$('#id').on('touchmove',function(){
alert("T");
});
$('#id').on('click',function(){
alert("T");
});
I have found the answer, I made div with invisible and placed the images with position absolute and use the id's of images and trigger the touchstart event.
above said example here
$('#id').on('touchmove',function(){
alert("T");
});
$('#id').on('click',function(){
alert("T");
});
<html>
<head>
<script type="text/javascript">
var curimage = "cottage_small.jpg";
var curtext = "View large image";
function changeSrc() {
if (curtext == "View large image"||curimage == "cottage_small.jpg") {
document.getElementById("boldStuff").innerHTML = "View small image";
curtext="View small image";
document.getElementById("myImage")= "cottage_large.jpg";
curimage = "cottage_large.jpg";
} else {
document.getElementById("boldStuff").innerHTML = "View large image";
curtext = "View large image";
document.getElementById("myImage")= "cottage_small.jpg";
curimage = "cottage_small.jpg";
}
}
</script>
</head>
<body>
<!-- Your page here -->
<h1> Pink Knoll Properties</h1>
<h2> Single Family Homes</h2>
<p>
Cottage:<strong>$149,000</strong><br/>
2 bed, 1 bath, 1,189 square feet, 1.11 acres <br/><br/>
<b id="boldStuff" />View large image
</p>
<p><img id="myImage" src="cottage_small.jpg" alt="Photo of a cottage" /></p>
</body>
</html>
This is my coding I need to change the image and text the same time when I click it.
I use LTS, it shows the line document.getElementById("myImage")= "cottage_large.jpg";
is a wrong number of arquments or invalid property assigment.
Dose someone can help?
Bianca
You need to do the following steps
Change document.getElementById("myImage") to document.getElementById("myImage").src
Change <b id="boldStuff" />View large image to <b id="boldStuff">View large image</b>
This will solve the problem
You'll need to change the image source.
document.getElementById("myImage").src = "cottage_large.jpg";
You should change :-
<b id="boldStuff" />View large image
to following:-
<b id="boldStuff">View large image</b>
Looks like the getElementById does not work well for empty tags If you dont use ending tag.
Complete correct source:-
<html>
<head>
<script type="text/javascript">
var curimage = "cottage_small.jpg";
var curtext = "View large image";
function changeSrc() {
if (curtext == "View large image"||curimage == "cottage_small.jpg") {
document.getElementById("boldStuff").innerHTML = "View small image";
curtext="View small image";
document.getElementById("myImage").src= "cottage_large.jpg";
curimage = "cottage_large.jpg";
} else {
document.getElementById("boldStuff").innerHTML = "View large image";
curtext = "View large image";
document.getElementById("myImage").src= "cottage_small.jpg";
curimage = "cottage_small.jpg";
}
}
</script>
</head>
<body>
<!-- Your page here -->
<h1> Pink Knoll Properties</h1>
<h2> Single Family Homes</h2>
<p>
Cottage:<strong>$149,000</strong><br/>
2 bed, 1 bath, 1,189 square feet, 1.11 acres <br/><br/>
<b id="boldStuff">View large image</b>
</p>
<p><img id="myImage" src="cottage_small.jpg" alt="Photo of a cottage" /></p>
</body>
</html>
KooiInc is correct. but there is one problem with this statement.
IE6 will not honour document.getElementById("myImage").src.
so i suggest you use jquery instead like this.
$('#myImage').attr("src","the new source path");
Update:
#CMS: Please do check what i am tryin to say.
well i suppose there is a terrible misunderstanding here. for as far as i know IE6 never honours changing image source directly using ".src=" technique. I always used to use the following technique to achieve it if i can't use jquery.
document.getElementById('ImageId').style.cssText="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='newPath');";