BannerBomb BannerBomb - 1 month ago 8
HTML Question

JavaScript is it possible to use var in your .html

before I start this is not a duplicate post



Sorry This post was marked duplicate they tried to say it was link a question that said "id can't be found by var" that is not my question



anyways...




Is it possible to use
var
codes in your HTML file but in a .js file you can have the rest of the script?

for example my code is

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// First Image
var image = document.getElementById('kximg0');
var link = document.getElementById('tooltipname');
var tooltipname = document.getElementById('tooltipname');
var namebelowimg = document.getElementById('namebelowimg');
image.src = "your image link for first image here";
link.title = "Movie title ex Batman (2008)";
tooltipname.href = "link to site when movie is clicked";
namebelowimg.innerHTML = "movie name here";
// End First Image
</script>
</head>
<body>
<p id="namebelowimg">this</p>
<img id="kximg0" src="this-is-a-image-link"><br>
<a id="tooltipname" title="title">img</a>
</body>
</html>


but is it possible to do this, if so how do I tell JavaScript to search for the id's between the
Body Tags
because the script is in the
Head Tag
and it only searches in the
head
tag but I don't wont the script in the body tag because it makes it easier to access in the
head
tag if this is not possible then is it possible to include the
var
in the html file and the script below the
vars
in a separate .js file? My example below should explain better.

html file



<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// First Image
var image = document.getElementById('kximg0');
var link = document.getElementById('tooltipname');
var tooltipname = document.getElementById('tooltipname');
var namebelowimg = document.getElementById('namebelowimg');
// End First Image
</script>
</head>
<body>
<p id="namebelowimg">this</p>
<img id="kximg0" src="this-is-a-image-link"><br>
<a id="tooltipname" title="title">img</a>
</body>
</html>


js file



// First Image
image.src = "your image link for first image here";
link.title = "Movie title ex Batman (2008)";
tooltipname.href = "link to site when movie is clicked";
namebelowimg.innerHTML = "movie name here";
// End First Image


If you need a better example go here

Answer

You getElementById won't work because scripts are executed before body is rendered. Simplest way to make it work is to move script tag after the body.

Other way might be to wait for body to load

<script>
function init(){
    var image = document.getElementById('kximg0');
    var link = document.getElementById('tooltipname');
    var tooltipname = document.getElementById('tooltipname');
    var namebelowimg = document.getElementById('namebelowimg');
}
document.addEventListener('DOMContentLoaded', init, false); //this event listener will wait until body is rendered
</script>