What does while javascript while(i<9) mean? - javascript

On this site about javascript shorthands, by Sam Deering, a long-hand example is as follows (the site uses a before-and-after format):
var i=0;
while (i<9)
{
//do stuff
i++; //say
}
While I don't understand this, I do understand the short-hand version, which is:
var i=9;
while(i--)
{
//goes until i=0
}
I don't know about if i is the same in both loops, but assume that they both loop 9 times.
Because I would like to expand my limits and improve my programming skills, what does the while (i<9) mean, and how can I use it (with other numbers)?

In XML, e.g. XHTML, you must escape < properly as <.
In HTML it's not necessary to do so inside script elements because their contents are parsed in a special way, but XML does not do these nasty things.
For example, you can write index.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Some document</title></head>
<body>
<script type="text/javascript">
var i=0;
while (i < 9) i++;
console.log(i); // 9
</script>
</body>
</html>
Most people don't want to XML-escape JavaScript operators in inline scripts, so they use CDATA sections:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Some document</title></head>
<body>
<script type="text/javascript">
<![CDATA[
var i=0;
while (i < 9) i++;
console.log(i); // 9
]]>
</script>
</body>
</html>

Your HTML file most probably has some encoding quirks. < corresponds to the less than symbol < in HTML entities. So really you can read that as while (i<9).

Related

Embedding JS and HTML at the same time fails

I would like to have many HTML pages of one type, the only difference being the page title and some data stored in different .json files. Everything else should be stored in two centralized files, a .js and an .html file. In pseudocode the pages should look like this:
<html>
<head>
include global_script.js
include specific_data_n.json
</head>
<body>
include global_body.html
</body>
</html>
where the n-th page includes the data file specific_data_n.json but everything else is always the same.
I know how to include .js and .json files in the header. However, I don't really know how to include the .html file in the body. I searched on the net and, in particular, found this question: Server side includes alternative I tried different ways of including the body proposed in the answers but whatever I tried, I got a JS error.
Here is a minimal example of the problem. First, the working file where the body is in the main file and not in an extra file:
function init(){document.getElementById('demo').innerHTML = '2+2=4';}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><head>
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<div id="demo">
2+2=5
</div>
</body>
</html>
Now I tried to put the body in an external file following one of the answers of the question linked above.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<!-- Content, inclusion from https://stackoverflow.com/questions/35249827/can-you-link-to-an-html-file -->
<div w3-include-html="body_minimal.html"></div>
<script>
(function () {
myHTMLInclude();
function myHTMLInclude() {
var z, i, a, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
if (z[i].getAttribute("w3-include-html")) {
a = z[i].cloneNode(false);
file = z[i].getAttribute("w3-include-html");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
a.removeAttribute("w3-include-html");
a.innerHTML = xhttp.responseText;
z[i].parentNode.replaceChild(a, z[i]);
myHTMLInclude();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
})();
</script>
</body>
</html>
and the body_minimal.html which is included:
<div id="demo">
2+2=5
</div>
I also tried different further approaches for embedding the body_minimal.html file (which I can present if needed) but none of them works, so I assume that it is some fundamental problem. I always get the error in the JS debugger:
TypeError: document.getElementById(...) is null
I need to add that I have no experience neither in HTML nor in CSS and am mostly copy&pasting stuff from different tutorials, forums and Q&A sites so I do not really understand what this code for the embedding of the HTML file is doing. :)
Thanks for any hint on what the problem might be and a happy new year!
This really belongs as a comment but unfortunately my account is new so I'm not allowed...An answer will have to do.
If your webhost runs PHP I'd suggest looking into PHP includes, they're much simpler.
Basically, you would save your central html file as a .php file instead and include the HTML file you want using
<?php
include 'global_body.html';
?>
Found a solution which looks stupid, but as you know, if something looks stupid but works, it isn't stupid. :) I just made another .js file which writes the body contents via document.write():
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript" src="script.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript" src="body.js"></script>
</body>
</html>
And the included .js files:
//body.js
document.write('<div id="demo"->2+2=5</div>');
and
//script.js
document.getElementById('demo').innerHTML = '2+2=4';
The only problem is that in a real world scenario the contents of the body are many lines and JS needs a backslash on each line break. Also, the syntax highlighting only shows all the HTML code in one colour as from JS's point of view it is just a string. Therefore I'm still interested in better/cleaner solutions!

how can I get text strings from list in txt document?

how would I do if I wanted to have an div on my site that contained a text and I wanted to replace that text every 5sec with a new text string that It got from an list from an external text file.
So something like this but in the "textlist" div it puts the first sting from the text file then 5 sec after it replaces that with the text from the second row, and so on.
CODE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test_text</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function run() {
document.getElementById("textlist").innerHTML = "The sting from the text file";
}
window.setInterval(run,5000);
</script>
</head>
<body>
<div id="textlist">the text</div>
</body>
</html>
and the text file would be like this for example:
/mytextfile.txt
(content in the file)
01: The tips 1
02: The tips 2
03: The tips 3
04: The tips 4
05: The tips 5
06: The tips 6
Thanks in advance hopes it make sense.
I'd do that a little differently:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test_text</title>
</head>
<body>
<div id="textlist">the text</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var ajax = $.ajax({
url: 'the url to the text list',
type: 'GET'
});
ajax.done(function (data) {
var list = $.trim(data).split(/\n+/), index = 0;
function run() {
if (index >= list.length) {
index = 0;
}
$('#textlist').html(list[index]);
index ++;
}
window.setInterval(run, 5000);
});
});
</script>
</body>
</html>
So in this example, we first move all of the scripts to the bottom of the body. That way we can be sure that our html has been rendered before the scripts run.
Secondly, we put our custom JavaScript into a jQuery docready. This way we are being extra safe that the page is fully interactive before our scripts try to run.
The next thing we do is use ajax to fetch the text file. Due to same-origin policy, this will only work if that file resides on the same server that is serving the web page.
After that, we attach a handler to the ajax promise. In other words, when the ajax request is "done", it will run a function and pass in the data that was retrieved. We turn the data into a list by trimming white space off the string and splitting it wherever there are new lines. We also set up a variable to track our place in the list.
The run function will check to see what place we are at in the list. If we've gone farther than the amount of items in the list, we'll reset it to 0. Then we'll replace the html of our element with the current list item. Finally we move up one place in the list.
Lastly we call setInterval so that run will run once every 5 seconds.
Caveat: I haven't tested this but conceptually it will work. There may be a typo or perhaps some specific ajax requirements I'm not aware of having to do with your server but the process I've described should work.
you can use ajax for that.with jquery (that is already attached to your document) you can easily do that as follow:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test_text</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var lines="";
$.get( "your_text_file_path", function( data ) {
lines=data.split("\n");
});
var i=0;
window.setInterval(function (){
if(i<=lines.length){
$("#textlist").html(lines[i]);
i++;
}else{
i=0;
}
},5000);
</script>
</head>
<body>
<div id="textlist">the text</div>
</body>
</html>
here you are a demo does that

Items added via appendChild method on a dropdown listbox are not displayed under IE8

Initially I thought it was a CSS issue but I built a small sample to repro the issue.
The values: Value1, 2 and 3 are not displayed if you use IE8:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert("Thanks for visiting!");
var gridCommandBox = $('#GridCommands')[0];
if (gridCommandBox.options.length == 0) {
gridCommandBox.options.add(new Option("<Select Command>", ""));
var clipGroup = document.createElement("optgroup");
clipGroup.label = "Copy To Clipboard...";
clipGroup.appendChild(new Option("Value1", "Value1"));
clipGroup.appendChild(new Option("Value2", "Value2"));
clipGroup.appendChild(new Option("Value3", "Value3"));
gridCommandBox.appendChild(clipGroup);
}
});
</script>
</head>
<body>
<table>
<tr><td><select id="GridCommands"></select></td></tr>
</table>
</body>
</html>
Any ideas?
Thanks
Max
An Option object is the HTML DOM object that is associated with an tag in HTML. You are instantiating an Option object directly and trying to append this JavaScript object to another DOM element.
While this may work for some browsers, you should be using document.createElement('option') to create the options. If you use the new Option approach, you may also have to add history.go(0) afterwards to force the browser to refresh the select options.

Validate Script tag within XHTML

The "span" tag is invalid, how do I make it valid?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
...
<script type="text/javascript">
var locations = [
[
'Kirklevington Village Hall',
'<span style="font-size:2;"><b>Kirklevington Village Hall</b>,<br />Forest Lane,<br />Kirklevington,<br />Stockton on tees,<br />TS15 9LX</span>',
54.4825,
-1.33663
]
];
</script>
Enclose your script in <![CDATA[ and ]]> to make it appear as a comment to the validator.
More info here
The simplest way is to put the script code to a separate file, say foo.js, and refer to it using <script "src=foo.js" type="text/javascript"></script>. Other methods involve various techniques for “escaping” the content of the script element, and they are clumsy and error-prone.
The XHTML 1.0 spec, appendix C, recommends: “Use external scripts if your script uses < or & or ]]> or --.”

Bug in Internet Explorer 7 element.getAttribute method

I'm implementing a length counter on textareas for a website (twitter style). I'm using the code found here http://www.codefromjames.com/wordpress/?p=15 but seems not to work in IE7.
I've traced the issue to the check of the attribute "maxlength" in an element. It expects it to be null if the attribute is not found, but IE7 returns a number (which I guess is the maximum length allowed by the browser or by the HTML standard, I don't know).
Here's an example you can try:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<head>
</head>
<body>
<input id="test"></input>
</body>
<script type="text/javascript">
var element = document.getElementById("test");
alert(element.getAttribute("maxlength"));
</script>
</html>
Try executing this on IE7 and you'll find out it gives a number instead of null.
Exact version of IE7 is 7.0.5703.13
Should I consider this a IE7 bug or is it working as expected?
Cheers!
You can check element.attributes.maxLength.specified to find out whether maxLength is indeed user-specified.
var element = document.getElementById('test');
var maxLength, defaultLength = 100;
if (element.attributes.maxLength && element.attributes.maxLength.specified) {
maxLength = element.attributes.maxLength.nodeValue || defaultLength;
} else {
maxLength = defaultLength;
}

Categories