Im trying to dynamically change a picture in html page according to a true/false condition using javascript.
If the variable is 0 an image and if it was 1 another picture should be shown in html page.
There are many pictures in a project that need to be changed i need a function that can do this application. But i dont know if it can be done with a single function or i should use a function for each variable.
Is siemens webserver the variable change is applied automatically by typing :="X":
when x is 0 instead of :="X": the number 0 is replaced and for the 1 instead of :="X": the number 1 is replaced.
Im familiar with html coding and how to change the picture using the image name and adding 0 or 1 after image name.
For example i name a picture stop0.png and another picture stop1.png . now in the html code i type stop:="X":.png in this way picture changes according to variable x
But this method needs the page to be refreshed to show the change. I want to do this in the easiest way possible without page refresh.
hmi should be designed in one page (for example named test.htm) and another html page with following code would update every thing in "test.htm" every second.
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>auto update page</h2>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "test.htm", true);
xhttp.send();
}
setInterval("loadDoc()", 1000);
</script>
</body>
</html>
Related
In the website I am working on, the content is loaded with Ajax, along with any JavaScript included. I am doing this because all the pages are of the same layout, but only the content is the different.
The problem is when a "content" has JavaScript in it, I was afraid the script will continue executing even after new content has been loaded. So I made this test to make sure.
First a main page that will load 2 other pages :
<script src="scripts/jquery.min.js"></script>
<script>
function loadPage1(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
response = xhttp.responseText;
$("#content").remove();
$("#mainContent").append(response);
}
};
xhttp.open("GET", "page1.html", true);
xhttp.send();
}
function loadPage2(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
response = xhttp.responseText;
$("#content").remove();
$("#mainContent").append(response);
}
};
xhttp.open("GET", "page2.html", true);
xhttp.send();
}
</script>
<button onclick="loadPage1()">Load page 1</button>
<button onclick="loadPage2()">Load page 2</button>
<div id="mainContent">
</div>
And then the 2 pages with JavaScript content, basically just spamming the console with "I am page x" every second.
Page 1:
<div id="content">
<h1>Page 1</h1>
<script type="text/javascript">
setInterval(function(){
console.log("I am page 1");
},1000);
</script>
</div>
Page 2:
<div id="content">
<h1>Page 2</h1>
<script type="text/javascript">
setInterval(function(){
console.log("I am page 2");
},1000);
</script>
</div>
The Ajax loads fine, I can see the h1 changing from Page 1 to Page 2. But in the console, I can see that the first script is still spamming even after the content has been removed.
Is there a way to prevent such behavior? Preferably while keeping each script in it's proper place, and not by moving all scripts to the "main page" .
EDIT: To avoid confusion, setInterval() is not the main problem, it's merely an example. I'm asking how do you usually deal with such a problem with Ajax and JavaScript
Even though the 1st <script> block has been replaced, you see the console logs because of the way javascript works.
Your anonymous function
function(){
console.log("I am page 1");
}
will live on and keep executing till you call clearInterval or move away from this page.
This is also the case when you add a click handlers eg $('#some_button').on("click",function(evt){/*do something*/});
Even if you have a variable declared, like <script>var x='data1';</script>
and then you delete the enclosing <script> tag, the variable x will continue to exist.
In both cases, the references to the functions and variables are stored somewhere. References to the setInterval, and click handler function are held by the event handlers. A reference to any var and function you declare is held in the window object (unless you use a closure).
In your newly loaded script, you could re-assign stuff: the behavior of a function will be the last loaded behavior. Any calls made to that function will execute the new instructions because they too have now been assigned to the window object(scope).
In summary,
You will need to clear interval
The functions and vars you declare will exist till you change them
Re:Question in comment
oh, so If I declare a new behavior for a function, it wouldn't give me an error like it would with static programming languages. It 2ould save me a lot of work if I can keep the namings the same. I guess all I need to do is clearInterval, and keep whatever functions as they are.
Right but rather than draw a parallel to other programming languages, try and see these as instructions that are interpreted immediately when you inject the script tag into the DOM. So, what you are doing is actually just re-assigning the properties of the window object. To understand this better, open the developer console on chrome and run these in order:
window.hasOwnProperty("xy")
var xy=1
window.hasOwnProperty("xy")
window.xy
xy="foo"
typeof window.xy
typeof window
This should help you understand how the JavaScript engine is treating your code.
You removed/replaced the content, not the script, you are still on the same page. also you only load new data into that page, so your script is still running in that page unless its stopped explicitly or when the page reloads.
I've got a chat function in my website for two users to chat with each other, and I'm using JavaScript, AJAX, and PHP for it.
At the moment, it won't refresh the chat area automatically unless I submit a reply to the chat or refresh the page. I can't figure out why.
JavaScript Function
function checkReply(threadid) {
// XMLHttpRequest
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("chatwrap").innerHTML = xmlhttp.responseText;
setInterval(checkReply(threadid), 10000);
}
}
xmlhttp.open("GET","inc/chatreply.php?chatid="+ threadid,true);
xmlhttp.send();
}
The event handler is on the <div> the responseText will end up in:
<div id="chatwrap" onload="checkReply('.$threadid.')"></div>
$threadid is a GET variable set at the top of the page:
$threadid = (int)$_GET['chatid'];
UPDATE
Seeing that you were in a PHP state already, the syntax was correct.
The problem is that the div doesn't possess an onload event. You'll have to attach it to the body tag, or include a script in the head or below the div, as it will only execute after the div has been rendered.
You're not including the PHP variable correctly. At the moment you are passing the string .$threadid. to the checkReply function. You will have to drop into PHP mode again before using this syntax by using the delimiters <?php & ?>.
<div id="chatwrap" onload="checkReply(<?php echo $threadid; ?>)"></div>
This should work better.
I am trying to code a java script function for my page. The "index.html" page has the basic layout with all the necessary tags (html, head, title and body). My question is, how will I go to the next page (if you click on a menu item) without having to code the same tags and copy all the data from the "index.html" page - i.e. not having redundant code.
e.g. There are 3 main pages excluding the "index.html" page (this one has all the main tags on it). The other pages are 1-About 2-Contact 3-Gallery. On each page the tags will only have:
Bla bla bla
some other tags with text, photos etc
What is the code for the java script function to change the text/content within the tags without having to copy the entire document's code on each page?
I want to use Chrome as the default browser and I am only using HTML and Java script (no PHP)
Thanks
Use can use this function this will solve your problem just pass your div Id where you want to load the contents of page with index layout. In my example i load my contents in container div.
/**
* Load page into url
*
* #param url The url to load
* #param onleave The function to call before leaving
* #param onenter The function to call after loading
*/
function loadPage(url, onleave, onenter)
{
alert(url);
console.log("loadPage("+url+")");
// If onleave function specified
if (onleave) {
onleave();
}
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
if (xmlhttp.status === 200) {
console.log("Received content"+xmlhttp.responseText);
document.getElementById('container').innerHTML = xmlhttp.responseText;
// If onenter function specified
if (onenter) {
onenter();
}
}
else {
document.getElementById('container').innerHTML = "Error loading page " + url;
}
}
};
xmlhttp.open("GET", url , true);
xmlhttp.send();
return;
}
Ok try this:
<!doctype html>
<html>
<head>
<script type="application/javascript">
function menuClick(x) {
if(x == "About"){
var menu1 = document.getElementById("menuButton_1");
menu1.innerHTML = "The HTML content for your about section";
} else if (){
// replicate the same for your other two menu sections
// here #2
} else if() {
// here #3
}
}
</script>
</head>
<body>
<div id="menuButton_1" onclick="menuClick('About')">
</div>
<div id="menuButton_2" onclick="menuClick('Contact')">
</div>
<div id="menuButton_3" onclick="menuClick('Gallery')">
</div>
</body>
</html>
You can execute an "onclick" function to fire when your menu buttons are clicked. In your javascript function you can test which menu button was clicked and set the innerHTML of particular elements on the page to show the correct content.
You can change the content of multiple elements by targeting each of their id's. Just create more javascript variables and use them to target the innerHTML of the specific HTML elements you want to change.
I have a site and I want it to randomly load a different HTML5 Javascript animation each time the page is loaded, JavaScript is by far one of the weakest of my skills and I appreciate any help in advance and if this happens to be duplicate (I've tried searching) then please vote for the question to be closed.
Basically the method I have used is a dirty one and most likely the reason its not working, basically I tried randommath and had no luck and put this down to my JS skills being extremely weak, the alternative method which looked easier doesn't work either and this is basically inserting a HTML on page load, so for example a.html and b.html which both contain different scripts.
This is what my code looks like:
HTML
<html>
<head>
<script src="js/insert.js"></script><!-- This inserts the Random Page -->
</head>
<body onload="loadExternalHTMLPage()">
<div id="injectjs"> </div>
<canvas="id"> </canvas>
<script src="js/animation-lib-pageA.js"></script><!--Library for pageA -->
<script src="js/animation-lib-pageB.js"></script><!--Library for pageB -->
</body>
</html>
Inject.js
function loadExternalHTMLPage() {
var xmlhttp;
var pagesToDisplay = ['a.html', 'b.html'];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("jsinsert").innerHTML = xmlhttp.responseText;
}
}
var randomnumber = Math.floor(Math.random() * pagesToDisplay.length);
xmlhttp.open("GET", pagesToDisplay[randomnumber], true);
xmlhttp.send();
}
Most JS Guru's should be able to see that I'm randomly inserting a.html and b.html on page load, now this works but the problem is the scripts contained within a.html and b.html are not executing. (using firebug I can clearly see that the scripts are being inserted as intended).
so for example a and b looks like:
a.html
<script> window.onload = function () { }</script>
b.html
<script> window.onload = function () { } </script>
Basically the code within A and B are valid and work fine within this insert and I've filled the above examples as just a placeholder. A and B both contain JavaScript that executes animation contained within the canvas but it doesn't work at present and I suspect its something to do with the fact I'm loading the scripts after the page has been loaded. Thanks in advance.
You can randomly load the html for A or B and then run its animation.
This example uses jQuery which makes the task of loading remote html easier. Here is a link to the jquery .load function which replaces an existing elements html with the downloaded html: http://api.jquery.com/load/ If you want pure javascript, you can use that [messier!] alternative, but the logic remains the same.
These are the steps:
Be sure the web page has loaded,
Randomly pick A or B to load/execute,
Replace the html in #injectjs with htmlForA or htmlForB,
Wait until the html has been fully replaced,
Run the appropriate animationA or animationB.
Here is starter code. (Be sure you include the jQuery library)
<script>
window.onload(){
// randomly load html+animation A or B
if(Math.random()<.50){
$('#injectjs').load(
'yourSite.com/HtmlForA.html', // first load the html for A
function(){ animationA(); } // then run animationA
);
}else{
$('#injectjs').load(
'yourSite.com/HtmlForB.html', // first load the html for B
function(){ animationB(); } // then run animationB
);
}
}
</script>
You can always use eval() to execute the content you downloaded ... :) (not recommended).
Or you can modify the html page on server to include the random script you want before serving the page to the user (you don't state platform) since it's anyways changed at page load.
I have a multi-level drop down menu (done using HTML + CSS) that I want to put on a number of different pages. In the future I will need to update this menu and change its contents, so I have saved the HTML in its own file so that I can roll out the changes to all the pages at once (instead of having to go through each page and repeatedly paste in the changed list items).
I have tried using iframe, but this cuts off the menu items with its limited height (setting a manual height that's big enough would leave tons of blank space, of course):
<iframe height="100%" src="menu.html" frameborder="no" width="100%" scrolling="no"></iframe>
I also tried using embed (this looks fine until you mouse over the menu items -- it just scrolls within the frame):
<embed type="text/html" src="menu.html" width="100%" height="100%"></embed>
The menu functions fine when the code is simply dumped into the individual pages I need it on, so I know that's not the issue. It's the embedding and calling it from its own HTML file that is the problem. Is there a simple way to do this that will allow the drop-down menu to appear as it should?
I should mention that while I have my IT department's blessing to do this, this is a project that they aren't supporting. I can only edit the HTML of my webpages in the body, and not the head. The exception being HTML pages I upload as files (like the menu code). So there are some constraints.
Well here is a bit of a long winded javascript approach that might keep your IT guys happy:
window.onload = new Function("load('embed-me.html','content')"); // Replace with URL of your file and ID of div you want to load into.
function ahah(url, target) {
document.getElementById(target).innerHTML = ' Fetching data...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
Not written by me(LINK) (I just added the run on page load bit).
Tested and working (in Chrome at least). Though your site will have no menu if the user has javascript disabled!
EDIT:
Example...
<body>
<script type="text/javascript" src="embed-me.js"></script> <!-- load the javascript -->
<div id="content"></div> <!-- html will be embedded here -->
</body>
I use the following php code and works very nice. It doesn't even show when you check the source code online.
<?php include("menu.php"); ?>
Use php Include !!
Okay first.. copy the menu code and save it on to a file called menu-1.php
then whenever you want to use your menu; just type the following code:
<?php include("menu-1.php"); ?>
This is a good way to do menu's because every time you need to update your menu, you wont have to update every single page, just update your menu-1.php
P.S. PHP might not show up on your local machine unless you are using wamp or xamp