I'm trying to generate a form for use with my game, I have to say, JavaScript is a whole new world from what I'm used to, and not being able to just create text-fields inside of the canvas is pretty lame, (Or atleast I haven't found a way to... that works with mobile devices)
Here's my code:
var loginForm;
var formUserInput;
var formSubmit;
loginForm = document.createElement("form");
loginForm.setAttribute('method', "post");
loginForm.setAttribute('action', 'doSomething()');
formUserInput = document.createElement("input");
formUserInput.setAttribute('type', "text");
formUserInput.setAttribute('name', "username");
formSubmit = document.createElement("input");
formSubmit.setAttribute('type', "submit");
formSubmit.value = "Submit";
loginForm.appendChild(formUserInput);
loginForm.appendChild(formSubmit);
document.getElementsByTagName('body')[0].appendChild(loginForm);
Here's my HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Online RPG Alpha </title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script src="js/engine/networking.js"></script>
<script src="js/engine/phaser.min.js"></script>
<script src="js/entity/Player.js"></script>
<script src="js/CanvasManager.js"></script>
</head>
<body>
<div id="game"></div>
</body>
</html>
When debugging the page I don't get any javascript errors, but the form never appears, and it also is not appended to the source. I also tried using $("body").append(loginForm); which is jQuery, but it also didn't work.
This is the generated HTML:
<html><head lang="en">
<meta charset="UTF-8">
<title>Online RPG Alpha </title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script src="js/engine/networking.js"></script>
<script src="js/engine/phaser.min.js"></script>
<script src="js/entity/Player.js"></script>
<script src="js/CanvasManager.js"></script>
</head>
<body>
<div id="game" style="overflow: hidden;"><canvas width="800" height="600" style="display: block; touch-action: none; -webkit-user-select: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); cursor: inherit;"></canvas></div>
</body></html>
The JavaScript is located inside of the "js/CanvasManager.js" script.
Since your JavaScript code is in an external file that is referred to via a script element in the head part, the code gets executed when the browser is still processing the head part and hasn’t even started reading the body element. Thus, there is no body element in the DOM, so the append fails. In the browser console log, you should see an error message like the following:
TypeError: document.getElementsByTagName(...)[0] is undefined
There are several ways to fix this. One way is to move the element
<script src="js/CanvasManager.js"></script>
at the end of the body, right before the end tag </body>.
A cleaner way is to wrap the code in a function and assign it to be executed once the page has loaded:
window.onload = function() {
// your current code goes here
};
This way the logic won’t depend on the placement of the script element.
Related
I am doing my damnedest to embed a Google trends chart into a section of my site.
In theory, it seems easy:
1.) copy script from Google:
2.) Clear a space in your webpage:
3.) Add the code:
<div class="full-row4" style="height: 300px;">
<script type="text/javascript" src="https://ssl.gstatic.com/trends_nrtr/1386_RC02/embed_loader.js"></script>
<script type="text/javascript">
trends.embed.renderExploreWidget("TIMESERIES", {"comparisonItem":[{"keyword":"/m/078rys","geo":"","time":"today 12-m"}],"category":0,"property":""},
{"exploreQuery":"q=%2Fm%2F078rys&date=today 12-m","guestPath":"https://trends.google.com:443/trends/embed/"}
);
</script>
</div>
Seems easy right? wrong!
Every time I do this, I get this result:
Upon further inspection, I found that when those scripts were loaded in, it wipes my entire body of the webpage. (Note: the chart gets loaded in thru an AJAX call containing the entire active page minus the navbars)
I've tried an array of different logic to try and get this to work, but everything I try deletes all HTML in the body tag of the webpage. (script tags are still there)
I found people with a similar issue, but it seems Google has changed how you embed these widgets into a site. Rendering any previous stackoverflow documentation useless. (at least from what I found)
you can use renderExploreWidgetTo() function instead, it takes DOM element as first parameter:
var divElem = document.getElementById('wrapper');
trends.embed.renderExploreWidgetTo(divElem,"TIMESERIES", {"comparisonItem":[{"keyword":"dbs bank","geo":"","time":"today 12-m"}],"category":0,"property":""}, {"exploreQuery":"q=dbs%20bank&date=today 12-m","guestPath":"https://trends.google.com:443/trends/embed/"});
Google trends embed script create an iframe at the hosting website.
Here is a simple example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>hello</h1>
<div>
<script type="text/javascript" src="https://ssl.gstatic.com/trends_nrtr/1386_RC02/embed_loader.js"></script> <script type="text/javascript"> trends.embed.renderExploreWidget("TIMESERIES", {"comparisonItem":[{"keyword":"dogs","geo":"","time":"today 12-m"}],"category":0,"property":""}, {"exploreQuery":"q=dogs&date=today 12-m","guestPath":"https://trends.google.com:443/trends/embed/"}); </script>
</div>
<h1>world</h1>
</body>
</html>
As you can see, the body is not affected.
The problem is probably not with the trends scripts, but a more general issue.
Try creating an iframe at your page, does it display correctly?
I am trying to instantiate a class in one JavaScript file in another HTML file but I keep on getting this error.
Here is the code for the JavaScript file:
class Puzzle {
constructor(fenStart, pgnEnd) {
this.fenStart = fenStart;
this.pgnEnd = pgnEnd;
}
}
And here is the code for the HTML. It should be noted that I am also using chessboard.js and chess.js and that everything is saved in the same folder.
<!DOCTYPE html>
<html>
<head>
<title>Chess</title>
<base href="http://chessboardjs.com/" />
<link rel="stylesheet" href="css/chessboard.css" />
</head>
<body>
<script src="js/chess.js"></script>
<div id="board" style="width: 400px"></div>
<p>PGN: <span id="pgn"></span></p>
<script src="js/json3.min.js"></script>
<script src="js/jquery-1.10.1.min.js"></script>
<script src="js/chessboard.js"></script>
<script src="class.js"></script>
<script>
var pgnEl = $('#pgn');
const x = new Puzzle("test", "test");
pgnEl.html(x.fenStart);
</script>
</body>
</html>
What is causing this error and how can I fix it?
This could be a result from improper file locations, like #sideroxylon said, js/class.js instead of class.js.
"The HTML <base> tag is used to specify a base URI, or URL, for relative links." https://www.tutorialspoint.com/html/html_base_tag.htm This could be another reason your file is inaccessible.
It could also be from certain URL's being blocked. Try opening Developer Console (CTRL-SHIFT-I or F12) and looking for any errors on your page.
If you're loading over HTTPS any content from an HTTP source may be blocked. Here is your exact code (using online versions of each library) but with the class.js file loaded in as a regular script tag and including the starting <body> tag.
https://jsfiddle.net/ckazwozg/ As you should see, it is working quite well.
Edit: For convenience, here is the raw source code from the JSFiddle.
<!DOCTYPE html>
<html>
<head>
<title>Chess</title>
<link rel="stylesheet" href="https://rawgit.com/oakmac/chessboardjs/master/src/chessboard.css" />
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js"></script>
<div id="board" style="width: 400px"></div>
<p>PGN: <span id="pgn"></span></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://rawgit.com/oakmac/chessboardjs/master/src/chessboard.js"></script>
<script>
// class.js
class Puzzle {
constructor(fenStart, pgnEnd) {
this.fenStart = fenStart;
this.pgnEnd = pgnEnd;
}
}
</script>
<script>
var pgnEl = $('#pgn');
const x = new Puzzle("test", "test");
pgnEl.html(x.fenStart);
</script>
</body>
</html>
I had the same error however what I did was ensure all my files are been saved to the root folder in your case I think that's js(since all your extension points to that location) in my case I've used only the file name after giving it javascript extension (.js) e.g...
I'm trying to make a web page where some of the elements are dynamically created. I wrote the following:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<p>Here's some example text</p>
<script type="text/javascript">
var jselem = document.createElement ("div");
jselem.innerHTML = '<p>and here\'s some more</p>';
</script>
</body>
</html>
However, the JS section does not seem to be doing anything, the text and here's some more is not printed.
Can anyone shed some light on why it is not working? Any help is appreciated.
(Please do not suggest using document.write() or similar.)
Use document.body.appendChild() (fiddle)
<script type="text/javascript">
var jselem = document.createElement("div");
jselem.innerHTML = '<p>and here\'s some more</p>';
document.body.appendChild(jselem);
</script>
You created the element, but didn't insert it into the document yet. That doesn't happen automatically -- until you do so, it's just a div floating around in memory.
See https://developer.mozilla.org/en-US/docs/Web/API/document.createElement
*Update: Ultimately I've decided that accomplishing exactly what I want here isn't possible due to the issues it poses to security. Kalle's answer below gives a solution that is closest to what I want to accomplish.
In order to solve my problem I've created scripts on both pages and will use a sort of push notification that is routed through the server in order for them to communicate.
Thanks for the help!! *
I have two pages. Both windows already exist independently. Page two has a function declared in JS.
I would like to be able to call the function in window two by clicking a link in window one.
Page 1:
<html>
<head>
<title>This is a title!</title>
</head>
<body style="background: lightblue">
Click Me!
</body>
Page 2:
<html>
<head>
<META HTTP-EQUIV="Window-target" CONTENT="my_target" />
<title>This is a title!</title>
<script type=text/javascript>
function clicked() {
alert('test');
}
</script>
</head>
<body style="background: lightblue">
</body>
Since it is on the same domain you can get this to work but would have to change the way you were doing it a little.
First off you would have to open it in a popup using this syntax rather than a new tab:
newwindow=window.open(url,'name','height=200,width=150');
and then you could simply call newwindow.clicked() after the popup is called.
update
just did a quick test and this will open it in a new tab. (sorry its been a while since I used the open function.
newwindow=window.open(url,'name');
Just noticed also that you should wait for the popup to load. So in my Example it would look a little something like this (with jQuery):
var newwindow = window.open('http://www.tylerbiscoe.com/vb/new.html');
$(newwindow).load(function(){
newwindow.clicked();
});
Ok, brand new answer. I hope this is what you were thinking. This is however, when you open page 2 from page 1.. So basically, page 1 would know who page 2 is..
Online example: http://kopli.pri.ee/stackoverflow/6832271.php
Page 1
<html>
<head>
<title>Page 1</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
.ajaxlink {color: blue; cursor: pointer; border-bottom: 1px dotted blue;}
</style>
</head>
<body>
<span id="open_page_2" class="ajaxlink">Open new window</span>
<br>
<br>
Click Me!
<script>
$('#open_page_2').click(function(){
child = window.open('test2.php','page_2','width=600,height=600');
});
$('a[target=my_target]').click(function () {
child.SecondPageFunction();
return false;
});
</script>
</body>
</html>
Page 2
<html>
<head>
<title>Page 2</title>
</head>
<body>
<h1>Your seeing page 2!</h1>
<script>
function SecondPageFunction () {
alert('Second page action got triggered!');
}
</script>
</body>
</html>
The script must be a part of the page you're opening in the new window. You're absolutely correct about it being a security flaw if it was elsewise allowed.
You could add some query string argument that could be picked up onload by javascript in the page you are opening and call your function if the query string arg is present.
I encountered a weird problem when trying to write a cross-browser script. Basically my header looks like this
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
Then in the body tag:
<p id="hey">Hey</p>
<input type="button" value="attachStyle" name="attachStyle" onclick="attachStyle();"></input>
<script>
function attachStyle() {
var strVar="";
strVar += "<style type='text\/css'>#hey {border:5px solid red;}<\/script>";
$("head").append(strVar);
}
</script>
The button works in Firefox, but not in Chrome. When I looked at the html DOM elements in the developer tool, the style tag was inserted but without content, like this:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style type='text/css'></script>
</head>
I'm curious as to what causes this? And how to create CSS style in a way that is cross-browser? Thanks!
<style type='text/css'></script>
You started with a "style" tag and closed it with "script". Wrong tag! :P