Javascript Check if number = variable - javascript

var Period =1;
if(Period==1){
document.getElementById("Main").style.backgroundImage = "url('Main_Background_Grass_1.png')";
}
For some reason this wont work. The image location is correct but im sure there is something wrong.
im pretty new to javascript
heres more code
<script type="text/javascript">
var Knowledge = 0;
var Period =1;
if(Period==1){
document.getElementById("Main").style.backgroundImage = "url('Main_Background_Grass_1.png')";
}
</script>
<div id="Main">
<div id="Toolbar">
Oh noes! Something Went Wrong
</div>
</div>
the image wont show up at all

The element isn't found at the time you call your function, place the javascript right before the closing body tag
<div id="Main">
<div id="Toolbar">
Oh noes! Something Went Wrong
</div>
</div>
<script type="text/javascript">
var Knowledge = 0;
var Period =1;
if(Period==1){
document.getElementById("Main").style.backgroundImage = "url('Main_Background_Grass_1.png')";
}
</script>

Uncaught TypeError: Cannot read property 'style' of null
That's because the element wasn't loaded yet. There are two ways to make sure a code runs only when a page is ready. One is to put the code at the bottom of the body, so the page has already been loaded. The other is to put it in an event listener for the window load event:
<script type="text/javascript">
window.addEventListener("load", function(e) {
// code goes here
});
</script>
Which one is the best practice? That's an eternal debate. I prefer the listener so that the code is all at the top, but many would disagree.

Related

javascript show variable in html

I'm trying to make a money display for a form which I am making, now I found this script on the web: http://jsfiddle.net/QQGfc/ And I'm trying to implement it into my code like this: (but it's not displaying the text.)
</script>
<script type="text/javascript">
document.getElementById("MyEdit").innerHTML = "My new text!";
</script>
With this in the body
<?php
include'includes/header.php';
include'includes/slider.php'; //carousel
?>
<h2>Contact Information</h2>
<div id="MyEdit">
This text will change
</div>
Ay idea whats going wrong?
You imply that the JavaScript is in the <head>.
When it runs, the <body> hasn't been parsed, so the element you are trying to modify does not exist.
Either:
Move the script to after the <div> you are trying to modify.
Wrap the script in a function and call that function after the <div> exists (e.g. by binding it as a load event handler).
you should do it after the DOM is completely loaded:
<script type="text/javascript">
window.addEventListener("load", function(){
document.getElementById("MyEdit").innerHTML = "My new text!";
});
</script>

How to stop a JQuery.load'ed inner scripts

I'm developing a dynamic web page with nested pages. Inner pages have their own script to be live and modular.
The problem comes when i want to remove one of the inner pages. Infact the HTML code is removed but the inner script keeps running.
Is it possible to stop the script?
This is a brief view of my solution:
Note that in this sample the ID are all the same but in the real solution they are identified by unique ID using php GET["ID"] value.
outerPage.php
<HEAD>
<script>
var fRunUpdate = true;
$(document).ready(function() {
$("#inner1").load("inner.php");
$("#inner2").load("inner.php");
$("#inner3").load("inner.php");
}
</script>
</HEAD>
<BODY>
<div id="inner1"></div>
<div id="inner2"></div>
<div id="inner3"></div>
</BODY>
innerPage.php
<HEAD>
<script>
var fRunUpdate = true;
$(document).ready(function() {
function update(){
//do something
$("#contentToUpdate").html("content");
setTimeout(update,1000);
}
}
</script>
</HEAD>
<BODY>
<div id="contentToUpdate"></div>
</BODY>
You will have to use stoptimeout or clear interval
I just read out this link and get it
How to stop a setTimeout loop?
Take function in variable
foo = setTimeout(function, time);
and then just clear it out
clearTimeout(foo);
I hope this will help you

onclick event not working, instead it triggering while page load

In the following code I simply want the number of matched element by tag name, But it returns 0 and it alerts while page load (not on click as I want). Cannot find any mistake over an hour
<!DOCTYPE HTML>
<HTML>
<head>
<script language="javascript">
document.getElementById("all").onclick = alert( document.getElementsByTagName("a").length);
</script>
</head>
<body>
<div id="all" class="a">Click</div>
<div class="a"></div>
<div class="a"></div>
</body>
</HTML>
I'm a total newbie in JavaScript
A couple of problems. The first one is pointed by #Ian in his comment on your question and the second one is you are calling getElementsByTagName("a") when in your code you do not have any <a> tags. You need to call getElementsByClassName("a") instead.
document.getElementById("all").onclick = function() {
alert( document.getElementsByClassName("a").length);
}
Update:
After Ian's comment, double checked jsfiddle and found that it had onLoad selected. So here is the corrected code with window.onload and updated jsfiddle:
window.onload = function() {
document.getElementById("all").onclick = function() {
alert( document.getElementsByClassName("a").length);
};
};
Here is the jsfiddle of this.
You are running the JS before even DOM is loaded. That means element all does not exist in the DOM when JS is running. Write like below, and that is the way to do.
var attachEve = function(){
document.getElementById("all").onclick = function() {
alert( document.getElementsByClassName("a").length);
}
}
window.onload = attachEve;
It should work!. Without window.onload works in jsfiddle because jsfiddle runs the JS in window.onload context.

appendChild on load

So the question is, why doesn't this append the div's on load? I'm scratching my head on this one. No errors... Just not loading.
<head>
<script type="text/javascript">
function load() {
var divTag0 = document.createElement("div");
divTag0.className = "newsBlock";
divTag0.innerHTML = " Try this..";
document.getElementById("newsLeft").appendChild(divTag0);
var divTag1 = document.createElement("div");
divTag1.className = "newsBlock";
divTag1.innerHTML = " Blah..";
document.getElementById("newsRight").appendChild(divTag1);
var divTag2 = document.createElement("div");
divTag2.className = "newsBlock";
divTag2.innerHTML = " And this ..";
document.getElementById("newsLeft").appendChild(divTag2);
}
</script>
</head>
<body>
<p> Something filler </p>
<div id="newsLeft">
</div>
<div id="newsRight">
</div>
<script type="text/javascript">
window.onload="load()";
</script>
</body>
You are supposed to supply a string to getElementById ...
So that:
document.getElementById(newsLeft).appendChild(divTag0);
Should be:
document.getElementById("newsLeft").appendChild(divTag0);
But the main problem is:
window.onload="load()";
Which should be:
window.onload=load;
Thanks to jvillars for the fiddle, which helped me notice this.
If azhrei's answer doesn't work, the only thing I could think of would be that calling onload after it has loaded might not trigger, you can change this from your example by simply calling load();
I tested it here
Hope this helps
EDIT:
I believe azhrei has the right of it, it's not so much that the onload isn't triggering, it's that there's a syntax problem with your onload call.
But this code can also be improved in terms of better style (more readable/ easier to comprehend) by removing the second JS call.
In the header if you write:
window.onload = function() {
//everything inside your load() function goes here
}
It works just as well. It also removes a lot of the fluff that was just kind of there. I hope that helps.

how does a function know where it is located in the DOM?

I'm trying to write a javascript function that adds some DOM nodes to the document in the place it was called, like this:
...
<div>
<script type="text/javascript">
pushStuffToDOMHere(args);
</script>
</div>
...
i try to do it 'cleanly', without using node id property of the div, or innerHTML string manipulation. for that I need to know where in the document the script tag is located.
is there a way to do it?
Talking about cleanly, I don't think your approach is particularly clean. It is a much better idea to give the div a unique id and execute your javascript when the DocumentReady-event fires.
Do you have an overriding reason for doing it this way? If not the suggestion to use a unique id makes the most sense. And you can always use a library like jQuery to make this even easier for yourself.
However, the following quick test shows that if you use document.write() in the function then it writes the value into the place where the function was called from.
<html>
<head>
<script type="text/javascript">
function dosomething(arg){
document.write(arg);
}
</script>
</head>
<body>
<div>The first Div</div>
<div>The
<script type="text/javascript">
dosomething("Second");
</script>
Div
</div>
<div>The
<script type="text/javascript">
dosomething("Third");
</script>
Div
</div>
</body>
</html>
But, again the question, are you sure this is what you want to do?
Although I agree with n3rd and voted him up, I understand what you are saying that you have a specific challenge where you cannot add an id to the html divisions, unless by script.
So this would be my suggestion for inlining a script aware of its place in the DOM hierarchy, in that case:
Add an id to your script tag. (Yes, script tags can have ids, too.)
ex. <script id="specialagent" type="text/javascript">
Add one line to your inline script function that gets the script element by id.
ex. this.script = document.getElementById('specialagent');
...And another that gets the script element's parentNode.
ex. var targetEl = this.script.parentNode;
Consider restructuring your function to a self-executioning function, if you can.
Ideally it executes immediately, without the necessity for an 'onload' call.
see summary example, next.
SUMMARY EXAMPLE:
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode.nodeName=="DIV" && this.script.parentNode;
//...your node manipulation here...
}('arg1','arg2','arg3');
</script>
The following TEST code, when run, proves that the function has identified its place in the DOM, and, importantly, its parentNode. The test has division nodes with an id, only for the purpose of the test. They are not necessary for the function to identify them, other than for testing.
TEST CODE:
<html>
<head>
<title>Test In place node creation with JS</title>
</head>
<body>
<div id="one">
<h2>Child of one</h2>
<div id="two">
<h2>Child of two</h2>
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode;
/*BEGIN TEST*/
alert('this.script.id: ' + this.script.id);
alert('targetEl.nodeName: ' + targetEl.nodeName + '\ntargetEl.id: '+targetEl.id);
alert('targetEl.childNodes.length: ' + targetEl.childNodes.length);
var i = 0;
while (i < targetEl.childNodes.length) {
alert('targetEl.childNodes.'+i+'.nodeName = ' + targetEl.childNodes[i].nodeName);
++i;
}
/*END TEST - delete when done*/
//...rest of your code here...to manipulate nodes
}('arg1','arg2','etc');
</script>
</div>
</div>
</body>
</html>
Not really sure what your trying to achieve but this would pass the dom element to the function when clicked. You could then use jquery in the function to do what you wanted like so
...
<script type="text/javascript">
function pushStuffToDOMHere(element)
{
$(element).append("<p>Hello</p>"); // or whatever
}
</script>
<div onclick="pushStuffToDOMHere(this);">
</div>
...
my solution is a compbination of the (good) answers posted here:
as the function is called, it will document.write a div with a unique id.
then on document.onload that div's parent node can be easily located and appended new children.
I chose this approach because some unique restrictions: I'm not allowed to touch the HTML code other than adding script elements. really, ask my boss...
another approach that later came to mind:
function whereMI(node){
return (node.nodeName=='SCRIPT')? node : whereMI(node.lastChild);
}
var scriptNode = whereMI(document);
although, this should fail when things like fireBug append themselves as the last element in the HTML node before document is done loading.

Categories

Resources