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
Related
Sorry there might be an answer somewhere out there, but I was having trouble finding it as well as trying to do it myself. But I was wondering if I could get an example of putting HTML inside of a jQuery function as well as a javascript function so that I can use it later to append to DOMs.
HTML
<div class="container>
</div>
jQuery
$(function (nothing){
'<h3>Nothing Here</h3>'
});
$(".container").append(function(nothing));
RESULT
Nothing Here
I am an even bigger noob with javascript, but I'd like to achieve the same result. Can someone show me how? Also, is there a difference in using the javascript method VS the jQuery method? thanks!
Javascript answer:
domElement.innerHTML is the API to add any html content inside the domElement.
And the html content can be returned from the javascript function in string format.
<!DOCTYPE html>
<html>
<body>
<div id="container">
</div>
<script> function getHTMLContent() {
return "<h2>Nothing here</h2>";
}</script>
<script>
document.getElementById("container").innerHTML = getHTMLContent();
</script>
</body>
</html>
Jquery answer: Instead of .innerHTML we have .append in jquery. This also takes string as parameter. And there is no difference in the way we call the javascript function.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function getHTMLContent() {
return "<h2>Nothing here</h2>";
}
$("#container").append(getHTMLContent());
});
</script>
</head>
<body>
<div id="container">
</div>
</body>
</html>
And regarding your doubt on function() and $function()..
$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
It gets called automatically once the page is ready.
But in javascript when you declare function(), this is not called by itself. You have to explicitly call it.
function nothing(){
$(".container").append('nothing');
}
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
Rookie alert!
Would you tell me why my Javascript code doesn't update the message. The browser runs HTML but ignores the Javascript code. What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
</html>
You're running the Javascript before you've loaded the body, the message element doesn't exist yet. Either move the script to the end of the <body>, or change the last line to:
window.onload = updateMessage;
so that the function will be loaded after the HTML is loaded.
If the <script> tag is in the <head> element, it gets executed before the HTML elements in the <body> are created. You can put your script tag inside the <body> element, at the end of it, to solve the issue.
Assuming you don't simply have javascript disabled, you could add a window.onload=function(){ surrounding your code.
window.onload=function(){
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
}
The reason for doing this is because your javascript code is inside your <head>. Thus, the javascript is loaded before the body. When the browser attempts to execute the javascript code, the message element isn't loaded yet and doesn't exist. By adding window.onload=function(){ to surround your code, your entire code will wait until the body is loaded before executing.
When you call your javascript code, the 'message' element isn't already there. I would suggest one of the following two things:
+Put your javascript code at the end of the body ( note that it only need to be after 'message', but putting it at the end is generally the best option )
+Replace your call with window.onload = updateMessage, which will wait until all the page is loaded to execute your javascript
There are already lots of duplicate answers here but there is another way, especially if you want to keep your Javascript code in a script tag in the head. And that is, wrap your Javascript function call in setTimeout -- this causes the function to be executed after the DOM has been parsed, but before the entire window has been loaded.
It's a neat little trick that can be used when you don't have a framework's (such as jQuery) document/ready functionality. window.onload or putting the script at the bottom might cause significant delays if there is lots of heavyweight content (large images?) in the page.
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
setTimeout(updateMessage);
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
</html>
Notice I have added a very large image to the page, but the updated message displays before the image fully loads.
If however instead of setTimeout(updateMessage); you use window.onload = updateMessage; as suggested in the currently accepted answer, your message will not get updated until the entire image loads (if you try this out, make sure you do a hard refresh after the first time so you are not getting it from your cache). Same goes for moving the script too far down the page (below the very large image for instance) as below. I honestly think, if you don't have a framework's document/ready functionality, using setTimeout in a script block in the head is the best solution.
MESSAGE NOT UPDATED UNTIL AFTER IMAGE LOADS:
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>
You are trying to make the changes before the DOM is loaded. See the code below,
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>
Alright, so I'm a complete noob at Html and require assistance. I have this piece of Javascript which calls a content locker
<script type="text/javascript" src="http://evodownload.com/content_locker.php?i=4l&s=1&c=0&o=1"></script>
JSfiddle: http://jsfiddle.net/TEHZd/
As you can see, the content locker appears as soon as the page loads, but I'd like it to appear after around 3 minutes. How can I do that?
I came up with this:
<head><script type="text/javascript">
function contentlocker(){
**NO CLUE WHAT TO TYPE HERE** <-- THIS IS WHAT I NEED HELP WITH MOSTLY
}
</script></head>
<body onLoad="setTimeout('delayer()', 1800)">
But I have no clue what to type as a function to call the locker.
Thanks in advance for your help :)
If you pass a string to setTimeout it gets evaluated using eval. Just pass the function reference instead setTimeout(delayer, 1800)
Assuming you've included JQuery...
setTimeout(function() {
doSomething();
}, 1000);
where 1000 is 1 second, so replace as appropriate.
<head><script type="text/javascript">
setTimeout(function() {
delayer();
}, 18000);
function delayer(){
div = document.getElementById("locker");
div.style.visibility = "visible";
}
</script></head>
<body>
<div id ="locker" style="visibility:hidden">
//PUT/LOAD YOUR LOCKER IN THIS DIV
</div>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does jQuery or a DOM method such as `getElementById` not find the element?
I've been trying to learn js, but im having trouble getting a very simple example to work and i cant seem to find what im doing wrong. From all i understand the below example should work. When i click on the second button, it calls the function f2 and outputs "batman" as an alert, so i know the javascript page is linked correctly. But when i click on the first button nothing happens.
HTML:
<head>
<script type="text/javascript" src="Positioning and flow tests.js"></script>
</head>
<body>
<p id="par1">Test</p>
<button onclick="f1()">Click me for par 1 content</button>
<button onclick="f2()">Click me for predefined text</button>
</body>
</html>
Javascript
// JavaScript Document
var var1 = document.getElementById("par1");
function f1()
{
alert(var1.innerHTML);
}
function f2()
{
alert("batman");
}
You have to put the JavaScript at the bottom of the page, otherwise the par1 element won't be available when your code runs:
<head>
<title>Positioning and flow tests</title>
</head>
<body>
<p id="par1">Test</p>
<button onclick="f1()">Click me for par 1 content</button>
<button onclick="f2()">Click me for predefined text</button>
<script type="text/javascript" src="Positioning and flow tests.js"></script>
</body>
An alternative to this, is to set your code to run when the page has finished loading:
var var1;
window.onload = function () {
var1 = document.getElementById("par1");
};
function f1()
{
alert(var1.innerHTML);
}
function f2()
{
alert("batman");
}
but this will wait until the page has completely loaded, which includes downloading all the images. If you were to click on the first button before all the images have been fully downloaded, you'd get an error.
You need to either put the code after the element or do this:
HTML:
<body onload="init()">
...
JS:
var var1;
function init() {
var1 = document.getElementById("par1");
}
function f1()
{
alert(var1.innerHTML);
}
The problem is you are trying to get an element that has yet to be created and therefore doesn't exist. Using an 'init' function will wait until the entire document has loaded before trying to get the elements.
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.