Variables in JavaScript: An error arrives [duplicate] - javascript

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.
When I am starting my website, the JavaScript does not work. Safari gives an error:
TypeError: 'null' is not an object (evaluating 'document.getElementById("aktuell").innerHTML')
This is my JavaScript-code:
<script>
var aktueller = document.getElementById("aktuell").innerHTML;
function go() {
neu = aktueller - 1;
document.getElementById("aktuell").innerHTML = neu;
if (neu == 1) {
document.getElementById("zweite").style.display = 'none';
document.getElementById("dritte").style.display = 'none';
}
else if (neu == 2) {
document.getElementById("dritte").style.display = 'none';
}
else if (neu == 0) {
document.getElementById("erste").style.display = 'none';
document.getElementById("zweite").style.display = 'none';
document.getElementById("dritte").style.display = 'none';
}
}
</script>
And this is my used body-part:
<body>
<p id="aktuell" style="display:none;" >0</p>
<center>
<button>Zurück</button><button onclick="go();">Weiter</button>
</center>
<div id="nullte"><img src="data/nullte.jpg" width="500px" /></div>
<div id="erste"><img src="data/erste.jpg" width="500px" /></div>
<div id="zweite"><img src="data/zweite.jpg" width="500px" /></div>
<div id="dritte"><img src="data/dritte.jpg" width="500px" /></div>
</body>

you have to wait until the page is completely loaded:
<script>
var aktueller = null;
window.onload = function(){
aktueller = document.getElementById("aktuell").innerHTML;
}
function go() {
//....
}
</script>
you can also do it like:
var aktueller = null;
window.addEventListener("load", function(){
aktueller = document.getElementById("aktuell").innerHTML;
});
the other option is to use onload event on body tag:
<head>
<script type='text/javascript'>
var aktueller = null;
function init(){
aktueller = document.getElementById("aktuell").innerHTML;
}
function go(){
//...
}
</script>
</head>
<body onload="init();">
</body>
although if you use jquery you have other options like:
var aktueller = null;
$(document).ready(function(){
aktueller = $("#aktuell").html();
});

When the script is evaluated, the Body is not yet built. You need to place the script and the end of the body, or put it inside of a document ready section, by using jQuery.
$(document).ready(function() {
var aktueller = document.getElementById("aktuell").innerHTML;
/* more code goes here */
});
More info here.
Why I would avoid using window.onload here.

Related

Localstorage resetting on refresh

I am currently attempting to learn Javascript and starting with a very basic incremental game where you click a button and it increases. I implemented a save button that properly saves to local storage, however upon refresh, it gets reset.
This is the local storage after hitting save, however, it gets reset to 0 when the page is refreshed.
I wanted to implement save functionality in the following way (see loadGame() and saveGame()):
// JavaScript Document
var saveState = {
food: 0
};
var GlobalFood = 0;
window.onunload = saveGame();
window.onload = loadGame();
function loadGame(){
var loadSaveStateString = localStorage.getItem('saveState');
saveState = JSON.parse(loadSaveStateString);
}
function saveGame(){
var saveStateString = JSON.stringify(saveState);
localStorage.setItem('saveState', saveStateString);
}
function tutorialFoodBtnFunc() {
var fVal = document.getElementById("GlobalFood");
GlobalFood++;
fVal.innerHTML = GlobalFood;
saveState['food'] = GlobalFood;
}
function tutorialFoodBtnFunc2() {
var fVal = document.getElementById("GlobalFood");
if(GlobalFood < 1)
{
var foodError = document.getElementById("foodErrorText");
foodError.classList.add("fade-in");
setTimeout(function (){
foodError.classList.remove("fade-in");
}, 2000)
}
else
{
GlobalFood--;
fVal.innerHTML = GlobalFood;
saveState.food = GlobalFood;
}
}
Here's my HTML as well if it's relevant:
<html>
<head>
<meta charset="utf-8">
<title>Wilderness</title>
<link rel="stylesheet" href="styling/tutorial.css">
<script src="js/main.js"></script>
</head>
<div id="page-wrapper">
<body>
<div id="nav">
<p class="GlobalVals">Foodstuffs: </p><span class="GlobalVals" id = "GlobalFood">0</span>
</div>
<div id="tutorialBody">
<button id="tutorialFoodBtn" onclick="tutorialFoodBtnFunc()">Gather Berries</button>
<button id="tutorialFoodBtn2" onclick="tutorialFoodBtnFunc2()">Eat Berries</button>
<p id="foodErrorText">You have no berries!!!</p>
<button id="tutorialFoodBtn2" onclick="saveGame()">Save!!</button>
</div>
</body>
</div>
</html>
First of all, onunload and onload should reference a function. (What you did is execute the function)
window.onunload = saveGame;
window.onload = loadGame;
Then, your code is properly loading the saveState, but you're not assigning it to your GlobalFood variable.
function loadGame(){
var loadSaveStateString = localStorage.getItem('saveState');
saveState = JSON.parse(loadSaveStateString);
GlobalFood = saveState.food;
var fVal = document.getElementById("GlobalFood");
fVal.innerHTML = GlobalFood;
}

Uncaught ReferenceError: AddAnime is not defined at HTMLInputElement.onclick (AnimeSite.html:51)

I'm making a quick site with a list and I can't call a function:
function:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
function AddAnime() {
var newItem = document.getElementById("div")
newItem.innerHTML = document.getElementById("box").value;
newItem.onClick = removeItem;
document.getElementById("list").appendChild(newItem);
}
</script>
</head>
But when I call it with this:
<input type="button" value="Add Anime" onclick="AddAnime();">
By the way, this is line 51
the error comes up.
I don't know what to do.
You need to expose the function outside of the onload scope:
<script>
function AddAnime() {
var newItem = document.getElementById("div") newItem.innerHTML = document.getElementById("box").value;
newItem.onClick = removeItem;
document.getElementById("list").appendChild(newItem);
}
window.onload = function() {
AddAnime();
}
</script>

how to pass return value fo a function to html div in Javascript

I need to pass generated Random number from JS function to the html div, but its not able to pass it on,here is my code snippet
<html>
<head>
</head>
<body>
<button id="order" onclick="getRand()">orderId</button>
<div id="order_id"></div>
<script>
var getRand = function () {
var elem = Math.floor(Math.random() * 89999 + 10000);
document.getElementById("order_id").innerHTML = elem.value;
};
</script>
</body>
</html>
Try with this: Working example :
<html>
<body>
<head><h1>CRS</h1></head>
<button id= "order" onclick="getRand()">orderId</button>
<div id="order_id">ff</div>
<script>
var getRand = function() {
var elem = Math.floor(Math.random()*89999+10000);
document.getElementById("order_id").innerHTML = elem;
};
</script>
</body>
</html>
You just change elem.value to elem
Check This Answers it is working good
var getRand = function() {
var elem = Math.floor(Math.random()*89999+10000);
document.getElementById("order_id").innerHTML = elem;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id= "order" onclick="getRand()">orderId</button>
<div id="order_id">ff</div>

Javascript - Share Variables over different <script> tags

I have one test.html file with two <script> tags. I need to share a variable from one to another..
Sample code:
<script type="text/javascript">
var test = false;
function testing() {
test = true;
alert('I am inside..');
}
testing();
</script>
...
<script type="text/javascript">
if (test == true) {
alert('working');
} else {
alert('failed');
}
</script>
The output is always:
I am inside..
failed
I also tried to use the window class but it doesn't matter.. (window.test)
What I have to do to get the 'working' alert?
Thanks if anyone can help me. I saw some similar questions, but the answers wasn't a solution for me.
EDIT:
The original code (simplified):
<head>
...
<script type="text/javascript" src="detectblocker.js"></script>
<!-- GitHub: https://github.com/sitexw/BlockAdBlock/ -->
...
</head>
<body>
<script type="text/javascript">
var blocker = false;
function adBlockDetected() {
blocker = true;
alert('inside');
}
if(typeof blockAdBlock === 'undefined') {
adBlockDetected();
} else {
blockAdBlock.onDetected(adBlockDetected);
}
blockAdBlock.setOption({
checkOnLoad: true,
resetOnEnd: true
});
</script>
<div class="header">
...
</div>
<div class="content_body">
<div class="requirs">
<ul>
...
<script type="text/javascript">
if (blocker == true) {
document.write("<li>enabled!</li>")
} else {
document.write("<li>disabled!</li>")
}
</script>
...
</ul>
</div>
</div>
...
</body>
The output is an alert() "inside" and the <li> "disabled".. (Blocker is enabled..).
The only difference I can see is on the end of the first <script> tag:
blockAdBlock.setOption({
checkOnLoad: true,
resetOnEnd: true
});
So why the snippet is working and my code not? Confusing...
If you do not use var before a variable it becomes a global variable like
test = true;
The variable test will be true during the page and also in your next scripts and functions.
Try this:
<script type="text/javascript">
var test = false;
function testing() {
var test = true;
alert('I am inside..');
}
testing();
</script>
...
<script type="text/javascript">
if (test == true) {
alert('working');
} else {
alert('failed');
}
</script>
There are two ways of doing it.
1) create a hidden element and set your variable from your first script to attribute of that element.
This is your hidden element
<input type="hidden" id="hiddenVar"/>
and can set it in javascript as
document.getElementById("hiddenVar").setAttribute("myAttr",test)
Now you can get it in next script as
document.getElementById("hiddenVar").getAttribute("myAttr")
2) By .data() you can read about it here

How to get the ParentElement of Object Tag?

I have a SVG graphic embedded via object tag.
<!DOCTYPE html>
<html>
<head>
<title>myTitle</title>
<script type="text/javascript" src="script.js"></script>
<link href="box.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id ="objectcontainer">
<div id="displaybox" style="display: none;"></div>
<object id = "mainSVG" type="image/svg+xml" data="map_complete.svg">
<img id="svgPic" src="map_complete.svg" alt="Browser fail"/>
</object>
</div>
</body>
</html>
In the SVG is a link:
<a id="emerBtn" xlink:href="emergency.html" onmouseover="return playVideo()" target="_parent">
The mouse over event should trigger the following:
function playVideo(){
//not working, all the time null
var doc = document.parentNode;
var elem = document.parentElement;
var otherElem = document.documentElement.parentElement;
//working if triggered from index.html
var thediv = document.getElementById('displaybox');
if(wasViewed == false) //show only one time
{
if(thediv.style.display == "none"){
wasViewed = true;
thediv.style.display = "";
thediv.innerHTML = "<div id='videocontainer'><video autoplay controls style='display:block; margin-left:auto;" +
"margin-right:auto; margin-top:150px; margin-bottom:auto; width:600px'>" +
"<source src='video.mp4' type='video/mp4'>HMTL5-Video not supported!</video>" +
"</div><a href='#' onclick='return palyVideo();'>CLOSE WINDOW</a>";
}else{
thediv.style.display = "none";
thediv.innerHTML = '';
}
} //close anyhow
else{
thediv.style.display = "none";
thediv.innerHTML = '';
}
return false;
}
My problem is, that i cannot access the "displaybox" from the svg.
I tried .parentNode, .parentElement, document.documentElement.parentElement etc.
But all the time the parent element/node is null.
Does anyone know how to access the "outer" HTML elements from the object/svg?
An SVG inside an object creates a nested browsing context.
To access elements outside this child document, you need to access the parent document:
function playVideo() {
// ...
var parentDoc = window.parent.document;
var displayBox = parentDoc.getElementById('displaybox');
// ...
}

Categories

Resources