This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 9 years ago.
Ok so I have this simplified code of what I am trying to do on this page. I want the browser to display a prompt as soon as they load the page asking for their name. Once they answer what their name is it takes that variable (name) and writes it inside of the div with the id "welcomeText". It just won't work for some reason... Please help thanks.
Heres my code. Put it all inside of a html index to make it easier to read.
<title>Welcome to Validus</title>
<style>
#welcomeText {
font-family:Verdana;
font-size:12px;
color:black;
width:100px;
height:100px;
margin:0px auto;
}
</style>
<script type="text/javascript">
var name=prompt("Hey! Welcome to Validus! Whats your name?", "Name");
document.getElementById("welcomeText").innerHTML = "Hey" + " " + name + "! " + "Welcome to validus...";
</script>
</head>
<body>
<div id="welcomeText">
</div>
</body>
Move the script to the bottom, just before the closing body-tag. Otherwise, 'welcomeText' doesn't yet exist on the page to refer to.
window.onload is launched when the page has finished loading.
there are also other many ways to acomplish what u need...
window.onload=func;
window.addEventListener('load',func,false);
window.addEventListener('DOMContentLoaded',func,false);
or just append your javascript at the end of your body tag. <script></script></body>
window.addEventListener('DOMContentReady',func,false);
using jquery...
the most common and compatible is window.onload.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Validus</title>
<style>
#welcomeText {
font-family:Verdana;
font-size:12px;
color:black;
width:100px;
height:100px;
margin:0px auto;
}
</style>
<script type="text/javascript">
window.onload=function(){
var name=prompt("Hey! Welcome to Validus! Whats your name?", "Name");
document.getElementById("welcomeText").innerHTML = name;
}
</script>
</head>
<body>
<div id="welcomeText"></div>
</body>
</html>
To demonstrate using document.createTextNode as per my comment.
Also see window.onload and addEventListener
Notes
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images and sub-frames have finished loading.
addEventListener is not supported on older versions of IE (IE < 9) and you need to use attachEvent instead.
HTML
<div id="welcomeText"></div>
CSS
#welcomeText {
font-family:Verdana;
font-size:12px;
color:black;
width:100px;
height:100px;
margin:0px auto;
}
Javascript
function doWelcome() {
window.removeEventListener("load", doWelcome);
var name = prompt("Hey! Welcome to Validus! Whats your name?", "Name");
document.getElementById("welcomeText").appendChild(document.createTextNode("Hey" + " " + name + "! " + "Welcome to validus..."));
}
window.addEventListener("load", doWelcome, false);
On jsfiddle
Here's an example using jQuery...
The key is using $(document).ready(function() {} ); so that the DIV exists in the DOM before the javascript tries to update it.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
table, tr, td {border:1px solid green;border-collapse:collapse;padding:5px 5px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
var name=prompt("Hey! Welcome to Validus! Whats your name?", "Name");
$("#welcomeText").html("Hey" + " " + name + "! " + "Welcome to validus...");
}); //END $(document).ready()
</script>
</head>
<body>
<div id="welcomeText"></div>
</body>
</html>
Related
I am making a very simple page that just counts how many seconds the user has had the tab open. In the console the seconds update, but on the page in the browser, it ain't.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.seconds = document.getElementById('counts');
var count = setInterval('counter()', 1000);
function counter(){
console.log(seconds)
document.getElementById('counts').innerHTML = window.seconds + 1;
}
</script>
<style>
h2 {
text-align:center;
color:#032441;
font-family:monospace;
}
div {
text-align:center;
color:#032441;
font-size:70px;
font-family:monospace;
}
</style>
</head>
<body>
<script>
document.body.style.backgroundColor = "#EBE9BD"
</script>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
What is the problem?
The variable seconds is declared too soon before the element is even rendered, that's why I added the window.onload wrapper to your code.
You need to use innerHTML to change the content of a div element.
Not related, but you can also style the body tag via CSS rule.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.onload = function () {
var seconds = document.getElementById('counts');
var count = setInterval(counter, 1000);
function counter(){
var newCount = Number(seconds.innerHTML) + 1
console.log(newCount);
seconds.innerHTML = newCount;
}
}
</script>
<style>
body {
backgroundColor: "#EBE9BD";
}
h2 {
text-align: center;
color: #032441;
font-family: monospace;
}
div {
text-align: center;
color: #032441;
font-size: 70px;
font-family: monospace;
}
</style>
</head>
<body>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
You could use the following:
<script type="text/javascript">
window.seconds = document.getElementById('counts');
setInterval('counter()', 1000);
function counter(){
console.log(seconds.innerHTML);
window.seconds.innerHTML++;
}
</script>
Bare in mind that 'counts' is not yet defined as soon as the script runs.
To access the "body" of an Element you have to access it via element.innerHTML which in your case would look like window.seconds.innerHTML = window.seconds.innerHTML + 1
EDIT: But that won't fix your problem.
Your script does not detect the <div id="counts"> element, since it has not been loaded yet, you can fix this by moving the script after the div
Since innerHTML returns a string, performing + will attach both strings and your seconds will look like 011111111 So you'll have to parse it to a string via parseInt(window.seconds.innerHTML)
So changing
window.seconds = window.seconds + 1
to
window.seconds.innerHTML = parseInt(window.seconds.innerHTML) + 1;
and moving the script tag at the very bottom, should to the trick
I have this code, and it is working fine on my test website but not in a browser as local (on my hdd) standalone page
Here it the code in jfiddle: https://jsfiddle.net/9jdsvjfb/
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
function toggleDiv(divId) {
var ele = document.getElementById(divId);
ele.toggle();
}
</script>
<style>
a:hover {
color: purple;
}
a:active {
color: purple;
}
</style>
<title></title>
</head>
<body>
<a class="ConceptLevel1" href="javascript:toggleDiv('PktS/h+L5EeSqM/4hMH9JA==');"
style="text-decoration: none; font-weight:bold; font-size:13pt">BGP -concept list</a>
<br />
<div style="padding-left:15px;" id="PktS/h+L5EeSqM/4hMH9JA==">
<div>fds</div>
<div>sdfdsfdfdsf</div>
<div>sdfsdf</div>
<div>gdhgf</div>
<a class="ConceptLevel2" href="javascript:toggleDiv('SPrQVTbDx0WO6As2F+43tw==');"
style="text-decoration: none; font-weight:bold; font-size:12pt">hfghg</a>
<br />
<div style="padding-left:15px;" id="SPrQVTbDx0WO6As2F+43tw==">
<div>hfghgh</div>
<div>fghfgh</div>
</div>
</div>
</body>
</html>
I can see two problems here. First, Divs doesn't have a toggle function; I think you mean:
function toggleDiv(divId) {
var ele = jQuery('#' + divId);
ele.toggle();
}
The other problem is in the jsFiddle: since jsFiddle sends all Javascript wrapped inside a function (in windows.load) it is needed to define the function toggleDiv as a global variable, for it to be found when clicking the link:
window.toggleDiv = function (divId) {
var ele = jQuery('#' + divId);
ele.toggle();
}
Just a final note: It may be better if instead of embedding the Javascript insite the HMTL, you use events in order to bind the toggle function to the links' click event.
When I open this page nothing happen. So what is the error on this code?
This is the code:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function code(){
var filename = loc.pathname.split("/");
filename = filename[pathname.length-1];
alert(filename);
<iframe src="http://url/" +currentPageUrl scrolling="yes" style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;">
Your browser doesn't support IFrames
</iframe>`
}
</script>
<title>Index</title>
</head>
<body onload="code();">
</body>
</html>
I am not sure what you are trying to do but there are lot of mistakes in your code.
loc should be location
just guessing that your trying something similar to this.
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function code() {
var filename = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
document.body.innerHTML = "<iframe src=" + filename + " scrolling='yes' style='position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;'>your browser doesn't support iframe<iframe>";
}
</script>
<title>Index</title>
</head>
<body onload="code();">
</body>
</html>
Because you don't have a valid script there.
loc is undefined.
You just have an iFrame tag flying around in your JS code.
There are several issues with this code:
loc looks like it's not defined. Maybe you want location
To add code to the DOM, you could use:
document.body.innerHTML = "<iframe src='http://' + variable ></iframe>"
Make sure all other variables are defined. i.e. use location.pathname when getting the length.
I am trying to learn some javascript, and have been writing my code as .js files and importing them to an index.html page.
Before all my errors were fixed, the page and canvas loaded properly. Now the page redirects before firebug can check for anything. And just displays the error "cannot find the file at [object Object]".
the index.html code is below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Life</title>
<script src='js/Map.js'></script>
<script src='js/Game.js'></script>
<script src='js/Animal.js'></script>
<script src='js/Block.js'></script>
<script src='js/Food.js'></script>
<script src='js/Shapes.js'></script>
<script src='js/Menu.js'></script>
<style>
#screen {
display:block;
margin:0 auto;
background-color:#000;
}
.fpsmeter {
padding: 0;
margin: 0;
width: 100%;
text-align: center;
}
.fpsmeter p {
margin-top: 0px;
margin-bottom: 0px;
}
</style>
</head>
<body>
<canvas id='screen' width='1200' height='500'></canvas>
<div id="fpscontainer"></div>
</body>
</html>
I'm not really sure where to look to find the solution to the problem.
https://dl.dropboxusercontent.com/u/23801920/Html5/life/index.html
Links to js files.
https://dl.dropboxusercontent.com/u/23801920/Html5/life/js/Animal.js
" "Block.js
" "Food.js
" "Game.js
" "Map.js
" "Menu.js
" "Shapes.js
I know there are probably a lot of other problems, but I'd just like help with this problem.
I believe ChiChou answered my question, but I have a bit of bug checking to do before I know for sure!
You must have missed new operator somewhere.
Check out the following code:
Animal = function (location, age, direction, dna, parentA, parentB){
//this = Block('animal');
this.type = 'animal';
this.age = age;
this.location = location;
^^^^^^^^
You should use var animal = new Animal() to create a new instance of Animal. If you directly call function Animal(), this inside the function will be a reference to window. Assigning value to window.location will make a redirection.
So you actually call something like:
window.location = location.toString();
Mofidy this.location to this._location will temporary solve this, but for a fundamental solution, you should find out where you call the function in a wrong way.
I'd like to display a div on a webpage when a user clicks on a button.
Does someone know how to do this ?
My code, so far, is :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
</head>
<body>
<input id="text" type="text" size="60" value="Type your text here" />
<input type="button" value="When typing whatever text display the div balise on the page" onclick="check();" />
<script type="text/javascript">
function check() {
//Display my div balise named level0;
}
</script>
</body>
</html>
Thanks,
Bruno
EDIT: All my code (I've erased it because it was too long and not very clear)
You can use document.createElement("div") to actually make the div. Then you can populate the div using innerHTML for the text. After that, add it to the body using appendChild. All told, it can look like this:
function check() {
var div = document.createElement("div");
div.innerHTML = document.getElementById("text").value;
document.body.appendChild(div);
}
This will add a div every time the button is pressed. If you want to update the div each time instead, you can declare the div variable outside the function:
var div;
function check() {
if (!div) {
div = document.createElement("div");
document.body.appendChild(div);
}
div.innerHTML = document.getElementById("text").value;
}
If you have the div already in the page with an id of "level0", try:
function check() {
var div = document.getElementById("level0");
div.innerHTML = document.getElementById("text").value;
}
A quick search on google gave me this example:
Demo of hide/show div
The source-code for that example is:
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<html>
<head>
<title>Demo of Show hide div layer onclick of buttons</title>
<META NAME="DESCRIPTION" CONTENT="Displaying and hiding div layers through button clicks">
<META NAME="KEYWORDS" CONTENT="Show layer, hide layer, display div, hide div, button on click, button on click event, div property, div style set">
<style type="text/css">
div {
position: absolute;
left: 250px;
top: 200px;
background-color: #f1f1f1;
width: 280px;
padding: 10px;
color: black;
border: #0000cc 2px dashed;
display: none;
}
</style>
<script language="JavaScript">
function setVisibility(id, visibility) {
document.getElementById(id).style.display = visibility;
}
</script>
</head>
<body>
<input type=button name=type value='Show Layer' onclick="setVisibility('sub3', 'inline');";><input type=button name=type value='Hide Layer' onclick="setVisibility('sub3', 'none');";>
<div id="sub3">Message Box</div>
<br><br>
</body>
</html>
Paste this code somewhere in your body
<div id="myDiv" style="display:none">
Hello, I am a div
</div>
Add this snippet into your check() function to display the otherwise-hidden content.
document.getElementById("myDiv").style.display = "block";
You could also change the div content programmatically thus:
document.getElementById("myDiv").innerHTML = "Breakfast time";
... would change the text to 'Breakfast time'.
You might want to look into jquery, it'll make your life 100 times easier.
Jquery is a javascript library (script) that you include and it allows you to manipulate the DOM very easily.
Start by adding the latest Jquery to your head which will allow you to use something like $(document).ready( )
The function inside .ready( fn ) is a callback function; it get called when the document is ready.
$("#lnkClick") is a selector (http://api.jquery.com/category/selectors/)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready( function() {
$("#lnkClick").click( function() {
$("#level0").attr("style", "display: block;width: 100px; height: 100px; border: solid 1px blue;");
});
});
</script>
</head>
<body>
<div id="level0" style="display:none;">
</div>
Click me
</body>
</html>
Of course this code can be made cleaner. You want to check: http://api.jquery.com/click/
There are plenty of examples.
Best of luck with Jquery!
you really should be using jquery , there's a little bit of a learning curve but once you get it, developing web apps is much easier.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script>
$(document).ready(function() {
$("#show_div_button").click(function() {
$("#div_to_show").show();
return false;
});
});
</script>
</head>
<body>
Click Me to Show the Div
<div style="display:none" id="div_to_show">I will be shown when the link is clicked</div>
</body>
</html>