Edited to explain page loading
My HTML page has a div inside another div, both referenced by id, and both unique throughout the document.
<head>
<script type="text/javascript" src="myscript.js"></script>
</head>
...
<body onload=display()>
<div id="rightwork">
<div id="mychart" > </div>
</div>
...
My JavaScript is meant to write something within the 'mychart' div, but I can't manage to reference it :(
The question is related to this one except this one is a class inside an id.
This is my javascript:
function display() {
var code = "<a onclick=\"second(); return false;\" href=\"#\">Hello</a>";
document.getElementById('rightwork').innerHTML = code;
}
function second() {
console.log(document.getElementById('rightwork'));
console.log(document.getElementById('mychart'));
}
The line
document.getElementById("mychart");
returns null...
Whereas, this one works fine!
document.getElementById("rightwork");
This returns the expected div.
I attempted this
document.getElementById("rightwork").getElementById("mychart");
which of course does not work as getElementById("rightwork") returns a single element.
So, what's the solution to reference the inner div?
Just use
window.onload = function(){
var myChart = document.getElementById("mychart");
// ... code that loads chart
}
Or move
<script type="text/javascript" src="myscript.js"></script>
to the page footer to insure the dom is loaded before running the script
Could you please post whole myscript.js content. If document is loaded correctly why document.getElementById("mychart"); would not work?
The thing might be that <div id="mychart" > </div> is not loaded while javascript is executed and <div id="rightwork"> was loaded in that time.
To ensure the document is fully loaded put your <script type="text/javascript" src="myscript.js"></script> at the end of html.
Related
I really don't know why this isn't working. In my HTML, if I put my script in the head section, I get the following error in my console:
Uncaught TypeError: Cannot read property 'addEventListener' of null
If I put my script in the bottom part of the body, it's working fine.
HTML :
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"> </script>
</head>
<body>
<ul>
<li> Shahin </li>
<li> Lina </li>
<li> Adrita </li>
</ul>
<img src="./img/1.jpg" class="hidden">
<img src="./img/2.png" class="hidden">
<img src="./img/3.jpg" class="hidden">
</body>
JavaScript :
var shahin = document.getElementById('img1');
var lina = document.getElementById('img2');
var adrita = document.getElementById("img3");
shahin.addEventListener('click',picShow);
lina.addEventListener('click',picShow);
adrita.addEventListener('click',picShow);
function picShow() {
console.log(this);
}
Can anybody tell me what I'm doing wrong and where is the proper place to put the script tag? Also, what change should I make to run my script from head section? I will be glad for your answer. Thanks in advance
Your script is loading and being executed prior to the rest of the body HTML, so naturally, document.getElementById is going to return null.
You should be running your event listener subscription code on or after the document.ready event.
Wrap the code you posted into a JS function, then set that function as the callback to be executed on document.ready:
document.addEventListener('load', initFn);
<script type="text/javascript" defer src="script.js"> </script>
Add key word defer, script runs when all DOM elements will loaded
If you put your <script> in the <head> javascript loading from top to bottom. So when loading it returns undefined eventlistener. So try use the script just before the end of your </body> tag and it will works.
Like so:
<script type="text/javascript" src="script.js"> </script>
</body>
Further to Josh E's answer:
You should be running your event listener subscription code on or after the document.ready event
If you want to execute your code as soon as the element is available, you can use requestAnimationFrame to scan the DOM during page load instead of waiting for the entire page to load:
function doSomethingWithElement(myElement) {
myElement.addEventListener('click', function() {
// Do stuff here
});
}
function searchForElement() {
const el = document.getElementById('img1');
if (el) {
return doSomethingWithEl(el);
}
window.searchID = window.requestAnimationFrame(searchForElement);
}
// Store the request ID so it can be cancelled later
// Otherwise it'll run forever!
window.searchID = window.requestAnimationFrame(searchForElement);
window.addEventListener('load', function() {
window.cancelAnimationFrame(window.searchID);
});
This might be overkill but it's super useful when you want to manipulate or add listeners to DOM elements as soon as is possible.
I'm trying to replicate this visualization here http://redotheweb.com/CodeFlower/ using my own json data. However the visualization is not showing up and I suspect it's because I have misplaced this block of code
var myFlower = new CodeFlower("#visualization", 300, 200);
myflower.update(jsonData);
which updates the visualization based on the content in the jsonData file. The full code is as follows:
<html>
<head> </head>
<body>
<div class = "content">
<div class = "container">
<p class = "lead"> </p>
<div id = "visualization">
<svg width = "270" height = "270">
var myFlower = new CodeFlower("#visualization", 300, 200);
myflower.update(jsonData);
</svg>
</div>
</div>
</div>
<script type = "text/java
<script type="text/javascript" src="javascripts/d3/d3.js"></script>
<script type="text/javascript" src="javascripts/d3/d3.geom.js"></script>
<script type="text/javascript" src="javascripts/d3/d3.layout.js"></script>
<script type="text/javascript" src="javascripts/CodeFlower.js"></script>
<script type="text/javascript" src="javascripts/dataConverter.js"></script>
<script type="text/javascript"> </script>
</body>
Please help. Thank you.
Your code is not quite correct. I think you can dispense with the SVG element, and move your CodeFlower initialization code to the empty script tag. Try this instead:
<html>
<head> </head>
<body>
<div class = "content">
<div class = "container">
<p class = "lead"> </p>
<div id = "visualization">
<!-- this empty div is what gets used by CodeFlower -->
</div>
</div>
</div>
<script type="text/javascript" src="d3.js"></script>
<script type="text/javascript" src="d3.geom.js"></script>
<script type="text/javascript" src="d3.layout.js"></script>
<script type="text/javascript" src="CodeFlower.js"></script>
<script type="text/javascript" src="dataConverter.js"></script>
<script type="text/javascript">
var myFlower = new CodeFlower("#visualization", 300, 200);
myFlower.update(jsonData);
</script>
</body>
</html>
According to the documentation:
Usage
To create a CodeFlower, include the CodeFlower.js file together
with d3.js, just like in this page. Create a new CodeFlower instance
using a CSS selector (of the div where the flower should be inserted),
and the width and height of the desired visualization. Then, bind JSON
data to the flower using CodeFlower.update(), and you're done.
CodeFlower creates the SVG element itself, inside the DIV that you provide. From the CodeFlower source code:
this.svg = d3.select(selector).append("svg:svg")
.attr('width', w)
.attr('height', h);
So adding your own SVG tag for CodeFlower is superfluous.
EDIT:
Make sure you have a valid jsonData variable: var jsonData = { /* json data here */ };
Here is a working fiddle: http://jsfiddle.net/2DUy9/1/
The block of code you're talking about is javascript, so it needs to be within script tags -- you've got a nice empty one at the end of your code. As is, your "code" is just being read as plain text. If it was inside a regular HTML element, the code would be displayed as text on the webpage, but text inside an SVG tag isn't even understood as plain text, since SVG is supposed to contain graphics.
Within the script you have to then indicate which SVG element you want to add the graph to. Just putting some code in the middle of your HTML doesn't make the results of the code go there -- even if it was put inside a script tag. However, the code you are borrowing is looking for the <div id="visualization"></div> tags, and should draw it there once you get your script formatted as #Colin recommended -- but only if your little bit of script comes after the script tag that imports the CodeFlower script. Otherwise, you'll just get an error in the console and nothing on the screen.
I'm afraid you're going to have to take some time to figure out what all the different parts of the program do before you can effectively adapt them to your needs.
The Mozilla Development Network has some good intro guides:
On HTML markup
On Javascript
For D3, the best intro for beginners without coding experience is the work of Scott Murray:
http://alignedleft.com/tutorials/d3/
My webpage has the following code:
<html>
<head>
<title>This is test Page</title>
<script language="javascript" type="text/javascript">
document.getElementById("msg1").innerHTML = document.URL.toString();
</script>
</head>
<body>
<div class="sss">
<p id="msg1"></p>
</div>
</body>
</html>
As you now at the time the script executes the div doesn't exist but I want to put my JavaScript code only In the <head> tag and I won't put it in middle of HTML code.
But this code only works when I put the <script> tag after the <div> tag.
I use VS2010 and firefox 19.0.1
Is there anyway to put code in <head> tag?
Your script relies on the DOM being ready, so you need to execute that function call only after the DOM is ready.
<script language="javascript" type="text/javascript">
window.onload = function() {
document.getElementById("msg1").innerHTML = document.URL.toString();
}
</script>
The various tags in your HTML page are loaded and processed in the order in which they appear on the page. Your <script> tag is executed immediately when it is parsed in the <head>. This is before the <body> and the elements inside the <body> are parsed. So, the script tries to reference an element that is not defined at the time it is executed.
Michael Geary is right, in order to execute your code, I'd use jQuery library (a de-facto standard in JS development) and utilize the DOM ready event. This will ensure the code in the handler will execute once DOM is fully loaded.
<script>
$(function(){
$('#msg1').html(document.URL.toString());
});
</script>
I recommend to to use addEventListener like this:
<script language="javascript" type="text/javascript">
document.addEventListener("DOMContentLoaded",() => {
document.getElementById("msg1").innerHTML = document.URL.toString();
});
</script>
Your script uses dom element and must run after the dom loaded.
Wrap your code in a function and call it after dom loaded
function myfunc(){
//code here
}
window.onload = myfunc();
i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.
I want to replace the current script tag with the HTML contents generated by the same script.
That is, my Page is
<html>
<body>
<div>
<script src="myfile1.js"></script>
</div>
<div>
<script src="myfile1.js"></script>
</div>
</body>
</html>
Inside each .js file corresponding html contents are generated. I want to put the contents as the innerHTML of the parent div. But can't set id for the parent div because the page is not static. So the current script tag must be replaced with the HTML content. How can I do this?
For each script tag src is the same. So can't identify with src. These scripts displays
some images with text randomly. Scripts are the same but displays different contents in divs on loading
Please help me
try inside of myfile1.js:
var scripts = document.getElementsByTagName( "script" );
for ( var i = 0; i < scripts.length; ++ i )
{
if ( scripts[i].src == "myfile1.js" )
{
scripts[i].parentNode.innerHTML = "new content";
}
}
This is a great question for those trying to implement a JSONP widget. The objective is to give the user the shortest possible amount of code.
The user prefers:
<script type="text/javscript" src="widget.js"></script>
Over:
<script type="text/javscript" src="widget.js"></script>
<div id="widget"></div>
Here's an example of how to achieve the first snippet:
TOP OF DOCUMENT<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
// inside of widget.js
document.write('<div id="widget"></div>');
$(document).ready(function() {
$.getJSON('http://test.com?remote_call=1', function(data) {
$('#widget').html(data);
});
});
<br />BOTTOM OF DOCUMENT
Have a look at: http://alexmarandon.com/articles/web_widget_jquery/ for the correct way to include a library inside of a script.
document.currentScript has been available since 2011 on Firefox and 2013 on Chrome.
document.currentScript documentation at MDN
<!DOCTYPE html>
<meta charset="UTF-8">
<title>currentScript test</title>
<h1>Test Begin</h1>
<script>
document.currentScript.outerHTML = "blah blah";
</script>
<h1>Test End</h1>
Unfortunately a running JavaScript file is not aware of where it is running. If you use document.write() in the script, the write function will take place wherever the script runs, which would be one way to accomplish what you want, but without replacing the contents or being able to perform any actions on the enclosing DIV.
I can't really envisage a situation where you'd have such stringent restrictions on building a page - surely if the page is dynamic you could generate identifiers for your DIV elements, or load content in a more traditional manner?
Why not use Smarty?
http://www.smarty.net/
You can use javascript in Smarty templates, or just use built-in functions.
Just take a look at http://www.smarty.net/crash_course
poof -- old answer gone.
Based on your last edit, here's what you want to do:
<html>
<head>
<!-- I recommend getting this from Google Ajax Libraries
You don't need this, but it makes my answer way shorter -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function getRandomContent(){
// I expect this is the contents of your current script file.
// just package it into a function.
var rnd = Math.random();
return "[SomeHtml]";
}
$('.random').each(idx, el){
$(this).html(getRandomHtmlContent());
});
});
</script>
</head>
<body>
<div class="random">
</div>
<div class="random">
</div>
</body>
</html>
If you don't mind the script tag remaining in place you can use something as simple as document.write().
myfile1.js:
document.write("<p>some html generated inline by script</p>");
It will do exactly what you need.