I need assistance on this JavaScript image display code - javascript

This is the code I am currently working with: I need to display a starting image (preferably green) and then, every time the button is clicked, the image needs to change to trafficlight and then to the other image which it didn't start as. e.g it needs to go from green to orange then red then back to orange etc.
<!DOCTYPE html/>
<html>
<script type="text/javascript">
var trafficlight = [];
trafficlight [0] = " http://4vector.com/i/free-vector-traffic-light-green- clip-art_117820_Traffic_Light_Green_clip_art_medium.png ";
trafficlight [1] = "http://www.clker.com/cliparts/8/1/7/4/11949849782053089133traffic_light_yellow_ dan_01.svg.med.png ";
trafficlight [2] = "http://www.clker.com/cliparts/1/f/a/2/11949849771043985234traffic_light_red_dan_ge_01.svg.med.png ";
var num = 0;
function changepic()
{
if (num>=trafficlight.length-1){
num=0;
}
num=num+1;
document.trafficlight.src=trafficlight[num];
}
</script>
</head>
<body>
<center>
<img src ="http://4vector.com/i/free-vector-traffic-light-green-clip- art_117820_Traffic_Light_Green_clip_art_medium.png" name="trafficlightpic" width="400" height="400" />
<p>click here</p>
</center>
</body>
</html>

As noted by Jonas W - you are trying to referecnce the image but using the wrong reference. You can either do it via an id or using the name as you have. Note that if you are using the name then you need to reference it with a [0] after it as I have in the post - this is because getting the element by name will return an array like object - so you need to specify that its the first item in that. Also your image src for the orange light is broken. The folowing works and allows swapping of the src (with the exception that the yellow light image does not display).
var trafficlight = ["http://4vector.com/i/free-vector-traffic-light-green-clip-art_117820_Traffic_Light_Green_clip_art_medium.png","http://www.clker.com/cliparts/8/1/7/4/11949849782053089133traffic_light_yellow_dan_01.svg.med.png","http://www.clker.com/cliparts/1/f/a/2/11949849771043985234traffic_light_red_dan_ge_01.svg.med.png"];
function changepic()
{
var imageSrc=document.getElementsByName('trafficlightpic')[0].src;
var num =trafficlight.indexOf(imageSrc);
if (num >= trafficlight.length-1){num=-1;}
num+=1;
document.getElementsByName('trafficlightpic')[0].src=trafficlight[num];
}
<center>
<img src ="http://4vector.com/i/free-vector-traffic-light-green-clip- art_117820_Traffic_Light_Green_clip_art_medium.png" name="trafficlightpic" width="400" height="400" />
<p onclick="changepic();">click here</p>
</center>

document.trafficlight doesn't exist. You need:
document.getElementById("trafficlightpic").src=trafficlight[num];
instead. And you should change name="" to id="" in the img element. That should work.

Related

JavaScript toggle behavior not working

I'm trying to create a simple toggle button with JavaScript and the else part is not working. The lamp is just turning on and then it stops working. How do I solve this?
<!DOCTYPE html>
<html>
<body>
<button onclick="toggleBulb()">Turn on/off</button>
<img style="margin-left:43%;border:1px solid rgb(50, 50, 50);padding:
20px;" id='light' src='../Media/lighton.gif'>
<script>
function toggleBulb() {
var doc = document.getElementById('light')
if (doc.src == '../Media/lightoff.gif') {
doc.src = '../Media/lighton.gif'
} else if (doc.src == '../Media/lighton.gif') {
doc.src = '../Media/lightoff.gif'
}
}
</script>
</body>
</html>
This is the difference between a property and an attribute. The attribute is the text in the HTML that you can see in the markup, but this is not always the same as the property by the same name. In this case, the property src is the evaluated URL represented by the src attribute. You'll notice that in my demo, I have a src attribute that begins with //, which tells the browser to use the current page's protocol for this resource, matching the page. The calculated property has https:// for the protocol because this stackoverflow page has an SSL installed. In the end, you should use .getAttribute() when comparing attributes.
<!DOCTYPE html>
<html>
<body>
<button onclick="toggleBulb()">Turn on/off</button>
<img style="margin-left:43%;border:1px solid rgb(50, 50, 50);padding:
20px;" id='light' src='//placehold.it/100/FF0/000?text=ON'>
<script>
function toggleBulb() {
var doc = document.getElementById('light');
if (doc.getAttribute('src') == '//placehold.it/100/000/FFF?text=OFF') {
doc.src = '//placehold.it/100/FF0/000?text=ON'
} else if (doc.getAttribute('src') == '//placehold.it/100/FF0/000?text=ON') {
doc.src = '//placehold.it/100/000/FFF?text=OFF'
}
}
</script>
</body>
</html>
As I mentioned in a comment the src is the full path on this file based on the website it's on. Instead one other you could do is check if the src ends with the string you are looking for:
function toggleBulb() {
var doc = document.getElementById('light')
if (doc.src.endsWith('/Media/lightoff.gif')) {
doc.src = '../Media/lighton.gif'
} else if (doc.src.endsWith('/Media/lighton.gif')) {
doc.src = '../Media/lightoff.gif'
}
}
Or you could check/set the full paths instead. Also not the else if can be made into just an else, unless you are planning to add more to that logic.
As others have said, your are checking the src property for an exact match, but that property will always return the full URL, and you aren't testing against full URLs, so you'll never get a match.
However, unlike the other answers, it's best to use .indexOf() to check the image source string to see if it contains a sub-string. Then it won't matter which value you get for the source (src attribute or full path). .indexOf() returns the index position of the substring or -1 if it can't be found.
Also, the if/then can be simplified using JavaScript's ternary operator:
<!DOCTYPE html>
<html>
<body>
<button onclick="toggleBulb()">Turn on/off</button>
<img style="margin-left:43%;border:1px solid rgb(50, 50, 50);padding:
20px;" id='light' src='//placehold.it/100/FF0/000?text=ON'>
<script>
function toggleBulb() {
var doc = document.getElementById('light');
// If the source contains "lightoff", set it to "lighton", otherwise set it to "lightoff"
doc.src = doc.src.indexOf('../Media/lightoff.gif') > -1 ? "../Media/lighton.gif" : doc.src;
}
</script>
</body>
</html>
You have to write full code at each and every place where you are comparing the images. Also doc.src returns A String, representing the URL of the image, including the protocol like- (http:///now here the full path of image.
if you code are running on localhost then file:///now here the full path of image.) I have added this in the code and it'll run correctly.
<!DOCTYPE html>
<html>
<body>
<button onclick="toggleBulb()">Turn on/off</button>
<img style="margin-left:43%;border:1px solid rgb(50, 50, 50);padding: 20px;" id='light' src='**insert your full path of image here**'>
<script>
function toggleBulb() {
var doc = document.getElementById('light');
if (doc.src== "file:///insert your full path of image here")
{
doc.src='insert your full path of image here';
}
else if (doc.src == "file:///insert your full path of image here") {
doc.src='full path of image here';
}
}
</script>
</body>
</html>

Trying to generate a random number for QRcode Javascript

I am trying to generate a QRcode using QRcode api website (http://goqr.me/api/). In order to have a random QRcode being generated I need a random number, right now this is what I have:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Gerar QRcode</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = Math.floor((Math.random() * 99) + 1);
document.getElementById("demo").innerHTML = x;
}
</script>
<img src = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=demo">
</body>
</html>
It generates a random number but it doesn't get to where it should be (after data=number here)
Can anyone please help me? Or guide me to the best way to do what I want.
EDIT: I want a new QRcode when I press the button "Gerar QRcode".
Since you're already using inline scripting, the following might be appropriate:
<script>
var x = Math.floor((Math.random() * 99) + 1);
document.write("<img src='https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x + "'>")
</script>
So the example page you posted would look like this:
<!DOCTYPE html>
<html>
<body>
<script>
var x = Math.floor((Math.random() * 99) + 1);
document.write("<img src='https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x + "'>")
</script>
</body>
</html>
EDIT:
To make it show a new QR code on button click (as mentioned in your comment), you'll need to change the src of the image to the new url. To do so, you'll also need a way to uniquely select the image you want to modify - it would probably be easiest to use an ID on the image tag and move the URL creation to a function.
This is very similar to what Caleb Mbakwe did in their answer:
<!DOCTYPE html>
<html>
<body>
<img id='qrcode' src=''>
<button onclick="newQR()">Gerar QRcode</button>
<script>
function newQR() {
var x = Math.floor((Math.random() * 99) + 1);
document.getElementById('qrcode').src = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x
}
newQR()
</script>
</body>
</html>
If you were just trying to get it working for testing the API, then this should be fine. Otherwise, please read a bit about Unobtrusive Javascript to clean up the code. Also, creating the img tag in javascript and then inserting it into the page might be a cleaner, longer-term solution.
From the api documentation, the QR code is the content of the data field of your request hence if you visit the url https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=demo in your browser, you will already see a QR code with the content being "demo".
What you need to do instead is concatenate your random number into the same field in your image source.
Something like this would suffice:
<script>
function myFunction() {
var x = Math.floor((Math.random() * 99) + 1);
document.getElementById("demo").src = document.getElementById("demo").src + x;
}
</script>
<img id="demo" src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=">
One solution would be to generate the url from the script.
<script>
function myFunction() {
var url = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=";
var x = Math.floor((Math.random() * 99) + 1);
url = url + x;
document.getElementById("demo").src = url;
}
</script>
<img id="demo" src="">
</body>
</html>

JavaScript set interval not working?

Could someone please explain why the following code below doesn't run an automated sequence of images'. I was able to do this before with my code prior to this now that I have edited it slightly the automation doesn't work.
<!DOCTYPE html>
<html>
<body>
<img id="Light" src="./red.jpg">
<button type="button" onclick="ChangeLights()">Change Lights</button>
<script>
var List = [
"./red.jpg",
"./redyellow.jpg",
"./green.jpg",
"./yellow.jpg",
];
window.onload = "ChangeLights()";
var index = -1;
function ChangeLights() {
index ++;
var image = document.getElementById('Light');
image.src = List[index % List.length];
}
setInterval(ChangeLights, 1000)
</script>
</body>
</html>
It works fine, but you can change Array to a different name and call ChangeLights(); without "" in line 18 .
The automation works, but the path to the images is wrong, you should fix that by pointing to the right folder, probably by removing the "./" on "./NAME_OF_THE_IMAGE".

TypeError: getElementById is null

<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>

JS Image change won't work under other tags (should be a simple fix)

Hey guys,
basically this is my page and the JS simply changes the images if one is clicked, this works grand if the <img src='worseun.png' name='worse' border='0' /> is first beneath the <body>, but doesn't work if there is another <img src='' /> above it! I'm still learning js and this is a head wreck, can anyone suggest a fix? Heres it working with nothing above
<script type="text/javascript">
function worseChange()
{
var theImga = document.getElementsByTagName('img')[0].src;
var xa = theImga.split("/");
var ta = xa.length-1;
var ya = xa[ta];
if(ya=='worseun.png')
{
document.images.worse.src='worse.png';
document.images.cd.src='cdun.png';
}
}
function cdChange()
{
var theImgb = document.getElementsByTagName('img')[1].src;
var xb = theImgb.split("/");
var tb = xb.length-1;
var yb = xb[tb];
if(yb=='cdun.png')
{
document.images.worse.src='worseun.png';
document.images.cd.src='cd.png';
}
}
</script>
</head>
<body>
<a name=1>Uno</a>
<img src='worseun.png' name='worse' border='0' /> <br />
<img src='cd.png' name='cd' border='0' />
<a name=2>Dos</a>
<body>
Thanks guys,
James
That first line:
var theImga = document.getElementsByTagName('img')[0].src;
means, "get the very first <img> tag in the document, and then fetch its 'src' attribute value." You can instead give the "real" image an "id" value, and use document.getElementById('whatever') to get it.
<img id='worse' src='worseun.png' name='worse' border='0' />
and then
var theImga = document.getElementById('worse').src;

Categories

Resources