Why Javascript Event Handler only works on the HTML page? [duplicate] - javascript

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

Related

Animating a walk cycle using only Javascript and HTML

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.

Varibla image source issue

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>

stuck with javascript-html output

I am kind of stuck in weird problem. i cant find the problem with the following code
<html>
<head>
<script type="text/javascript">
// Import GET Vars
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
var tag_tag=document.$_GET['tags'];
alert(tag_tag);
document.getElementById("resultElem4").innerHTML=tag_tag;
</script>
</head>
<body>
<p id='resultElem4'></p>
</body>
</html>
its showing the string in alert but not in html when i call it like result.php?tags=cat
Put your script tag at the bottom (right before the closing body tag). The issue is that the element resultElem4 hasn't loaded when you try to reference it using getElementById.
You just move the < script > to the end of the body.
<body><p></p><script>....</script></body>

Why can't javascript find my functions?

I made a puzzle game using HTML5, just now I tried to add local storage to the game, but failed.
I wrote three functions. The problem is: If I put all the functions in one .js file, none is defined when debugging(via chrome). If I split these three functions to another file and add a tag to the .html file, I'm told these are not defined.
So how to solve this problem?
Sorry for my poor English, hope you understand what I means.
Here are my functions and html file.
<html>
<head>
<meta charset="utf-8">
<title>Puzzle</title>
<script src="puzzle-localstorage.js"></script>
<script src="puzzle.js"></script></script>
</head>
<body onLoad="Init()" onkeydown="keydown()">
<p align="center">
<canvas id="board" height="600" width="600" style="border-style:double">
Your Browser doesn't support canvas
</canvas>
</p>
<p id="moves">Moves: <span id="movecount">0</span>
<input type="number" id="boardEdgeNum" value="3"/>
<input type="file" id="imgSrc"/>
</p>
function supportsLocalStorage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
function saveGameState() {
if (!supportsLocalStorage()) { return false; }
localStorage["puzzle.boardEdge"] = boardEdge;
localStorage["puzzle.blockPixel"] = blockPixel;
for (var i = 0; i < boardEdge; i++) {
for(var j=0;j<boardEdge;j++){
localStorage["puzzle.gameStatus."+i+j] = gameStatus[i][j];
}
}
localStorage["puzzle.image.src"]=imgElement.src;
localStorage["puzzle.move.count"] = moveCount.textContent;
if(gameInProgress)localStorage["puzzle.game.in.progress"] = "true";
else localStorage["puzzle.game.in.progress"]="false";
localStorage["puzzle.empty.block.X"] = emptyBlock.X;
localStorage["puzzle.empty.block.Y"] = emptyBlock.Y;
return true;
}
function resumeGame() {
if (!supportsLocalStorage()) {return false;}
if(!localStorage["puzzle.game.in.progress"]=="true"){return false;}
boardEdge=parseInt(localStorage["puzzle.boardEdge"]);
blockPixel=parseInt(localStorage["puzzle.blockPixel"]);
imgElement=new Image();
imgElement.src=localStorage["puzzle.image.src"];
gameStatus=new Array(boardEdge);
gameCompStatus=new Array(boardEdge);
for (var i = 0; i < boardEdge; i++) {
gameStatus[i]=new Array(boardEdge);
gameCompStatus[i]=new Array(boardEdge);
for(var j=0;j<boardEdge;j++){
gameStatus[i][j]=parseInt(localStorage["puzzle.gameStatus."+i+j]);
var x=(gameStatus[i][j]-1)%boardEdge;
var y=(gameStatus[i][j]-1-j)/boardEdge;
drawingContext.drawImage(imgElement,x*blockPixel,y*blockPixel,blockPixel,blockPixel
j*blockPixel,i*blockPixel,blockPixel,blockPixel);
drawLines();
}
}
gameStatus[boardEdge-1][boardEdge-1]=0;
gameCompStatus[boardEdge-1][boardEdge-1]=0;
moveCount.textContent=localStorage["puzzle.move.count"];
gameInProgress=(localStorage["puzzle.game.in.progress"] =="true");
emptyBlock=new Cell(parseInt(localStorage["puzzle.empty.block.X"]),parseInt(localStorage["puzzle.empty.block.Y"]));
return true;
}
<script src="puzzle.js"></script></script>
What is this? Is it typo? Or in your real code it is so too? Try to remove them. Javascript should see your functions. Where is declarations for Init and keydown functions? Does javascript see them?
Have you checked for any errors? I see one in the loop of resumeGame:
drawingContext.drawImage(imgElement,x*blockPixel,y*blockPixel,blockPixel,blockPixel
j*blockPixel,i*blockPixel,blockPixel,blockPixel);
should probably be:
drawingContext.drawImage(imgElement,x*blockPixel,y*blockPixel,blockPixel,blockPixel,
j*blockPixel,i*blockPixel,blockPixel,blockPixel);
Your url might be wrong. You are using a relative url instead of an absolute url, consequently the JS file must be in the same folder as the HTML Document.
Try an absolute url (e.g. http://www.servername.com/puzzle/js/puzzle.js") instead and check if that accomplishes anything.

Using Google Images API

I'm trying to use Google's Images API to search an image and put it into my html document as a div. This is what I have so far, but nothing seems to be appearing. This is parts from http://code.google.com/apis/imagesearch/v1/devguide.html. This is my first time using an API, so I'm not sure what is really going on.
<html>
<head>
<title>Art Project FTW</title>
</head>
<body>
<br>
<br>
<form name="upload" method="post" action="parse_image.php" enctype="multipart/form-data">
<input type="file" name="Image"><br>
<input type="submit" value="Upload Image">
</form>
<script type="text/javascript" src="https://www.google.com/jsapi?key=xxx"></script>
<script type="text/javascript" charset="utf-8">
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = searcher.results;
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var title = document.createElement('h2');
// We use titleNoFormatting so that no HTML tags are left in the title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(title);
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
}
}
function onload() {
// Our ImageSearch instance.
var imageSearch = new google.search.ImageSearch();
// Restrict to extra large images only
imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
google.search.ImageSearch.IMAGESIZE_MEDIUM);
// Here we set a callback so that anytime a search is executed, it will call
// the searchComplete function and pass it our ImageSearch searcher.
// When a search completes, our ImageSearch object is automatically
// populated with the results.
imageSearch.setSearchCompleteCallback(this, searchComplete, [imageSearch]);
// Find me a beautiful car.
imageSearch.execute("Subaru STI");
}
google.setonloadCallback(onload);​
</script>
</body>
</html>
Thanks in advance!
It can't work because you are looking for a HTMLElement that has the ID='content', you haven´t anyone element with that ID
Try putting your js functions within <head></head>

Categories