What I want to do is that: a webpage with continuously updating content. (In my case is updating every 2s) New content is appended to the old one instead of overwriting.
Here is the code I have:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.write(number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
var my_interval = setInterval('send_msg()', 2000);
However, in both IE and Firefox, only one line is printed out, and the page will not be updated anymore. Interestingly in Chrome, the lines are being printed out continuously, which is what I am looking for.
I know that document.write() is called when the page is loaded according to this link. So it's definitely not the way to update the webpage continuously. What will be the best way to achieve what I want to do?
Totally newbie in Javascript. Thank you.
Lily
I would have a div or some other container, like this:
<div id="msgDiv"></div>
Then write to it like using .innerHTML, like this:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.getElementById("msgDiv").innerHTML += number + " " + msg_list[number%4]+'<br/>';
number++;
}
var my_interval = setInterval(send_msg, 2000);
You can see a working example of this here
You can append to the innerHTML property:
var number = 0;
function send_msg()
{
document.getElementById('console').innerHTML += (number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
This code will append the message to an element with an id of console, such as
<div id="console"></div>
By the way, it is bad practice to call setInterval with a string.
Instead, pass the function itself, like this:
var my_interval = setInterval(send_msg, 2000);
I would start by looking at the jQuery library. This will save you a lot of pain.
What you want to do is keep inserted lines into a table, using eg:
$('table tbody').append('<tr><td>some value</td></tr>');
This would be an excellent opportunity for you to learn a little DOM programming.
Using the DOM to update the page should result in less overhead than simply concatenating more HTML into it. Find the node you want to put the updates into, and do an appendChild on each subsequent addition.
The answers to this question may be helpful: What's a simple way to web-ify my command-line daemon?
Related
This is what I am doing: I am building a fun in house API Voting System. I am using a client side snippet insert onto page
Like this:
<script src="domain.com/api/scripts/main.js"></script>
<div id="content-wrap" id="ac1e435e-c564-48f8-9f45-338616e7a789"></div>
Now in my main .JS I do all ajax request and modify the #content-wrap with creating new elements and inserting additional JS required to run Voting System.
However big issue I am experiencing is when I write JavaScript that I need to insert into #content-wrap I am currently writing it like this:
script.innerHTML = "$(someting).on('click', funciton(){"
+ "$.ajax({type: 'post',"
+ " url: '" + base + "/api/request', data: $('form').serialize(), "
+ "success: function(response){";
As you can see that can cause lot of issues as I build on it.
What is better way to accomplish this or is there a way i can just write my script / code and do something like this.
script.innerHTML = ConvertToString(script.js) OR ConvertToString(function X);
ConvertToString is just an expression I am using to explain what I would like to do instead of what I am doing.
Thank you, I am open to any suggestions.
I also must do this in plain JavaScript or with jQuery library so any suggestions to use VueJs, AngularJS or React will be considered as future references.
Thank you again
Additional explanation:
I would like to insert into my script element JavaScript snippet. But my snippet is about 30 lines long currently and might get bigger with time so it is very difficult to code with all the + " code " on every line that I write so that it can be inserted with innerHTML into element and executed on Client end.
So I would instead like to do something like this
element.innerHTML = mysnippetcode // but with out using + "" on each line like shown above
OR
element.append(snippet)
I hope this makes it little more clear
Solution that worked for me was using back ticks to wrap my sinppet and insert it into innerHTML of the element..
Just use the function's name without the () to convert it to a string:
function foo() {
var a = 10;
var b = 20;
var c = a + b;
return c;
}
document.write(foo);
The document.write will result in this string:
function foo() { var a = 10; var b = 20; var c = a + b; return c; }
If you only want the function's body, then you could just normally remove the first and last characters of the string.
I am not entirely sure this is what you wanted, if not, please make yourself more clear.
Alternatively, you could do an eval([insert function code here]) and there would be no need to add the code to the innterHTML of the script, read up on that function if you haven't heard of it.
Or if you want to create a function from a string, you can use new Function([name] ,[function body string]) if you need arguments you have to sandwich them between the 2 parameters.
But my snippet is about 30 lines long currently and might get bigger with time > so it is very difficult to code with all the + " code " on every line that I
write
You can use template literals if you want multi-line strings in Javascript, you simply have to replace your quotes with backticks.
See this MDN page if you are interested, or even this StackOverflow answer.
I need to create a javacript function that downloads the html source code of a web page and returns the number of times a CSS class is mentioned.
var str = document.body.innerHTML;
function getFrequency(str) {
var freq = {};
for (var i=0; i<string.length;i++) {
var css_class = "ENTER CLASS HERE";
if (freq[css_class]) {
freq[css_class]++;
} else {
freq[css_class] = 1;
}
}
return freq;
};
What am I doing wrong here?
What am I doing wrong here?
I hate to say it, but fundamentally... everything. Getting information about HTML does not involve string functions or regular expressions. HTML cannot be dealt with this way, its rules are way too complex.
HTML needs to be parsed by an HTML parser.
In the browser there are two possible scenarios:
If you work with the current document (as you seem to do), then the parsing is already done by the browser.
Counting the number of times a CSS class is used actually is the same thing as finding out how many HTML elements have that class. And that is easily done via document.querySelectorAll() and a CSS selector.
var elements = document.querySelectorAll(".my-css-class");
alert("There are " + elements.length + " occurrences of the class.");
If you have an HTML string that you loaded from somewhere, you need to parse it first. In JavaScript you can make the browser parse the HTML for you very easily:
var html = '<div class="my-css-class">some random HTML</div>';
var div = document.createElement("div");
div.innerHTML = html; // parsing happens here
Now you can employ the same strategy as above, only with div as your selector context:
var elements = div.querySelectorAll(".my-css-class");
alert("There are " + elements.length + " occurrences of the class.");
I have four dynamic variables in my program,
xzero, xone, xtwo, xthree
That represent the coefficients of a cubic function. I want to show the actual equation in the HTML, in the following format:
xthree*x^3+xtwo*x^2+xone*x+xzero=f(x)
but it needs to be able to update with the variables, so I had originally thought that I would do a
document.getElementById("demo").innerHTML = (new equation);
But it seems to me that either mathJax doesn't work in javascript, or that I'm not doing it right. The only alternative solution that I could think of is to make four individual div tags per variable, and update them all, but this seems unnecessarily clunky. Could I get some pointers either way as to how I would fix this?
MathJax automagically renders the document when it is loaded, but not later. Try explicitly requesting re-render:
document.getElementById("demo").innerHTML = "...";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, 'demo']);
EDIT: After some thinking, I figured you could ask for the render in one element, keep it hidden, then copy the finished markup into another, to prevent flicker:
var mathDiv = document.getElementById('math');
var displayDiv = document.getElementById('display');
MathJax.Hub.Queue(["Typeset",MathJax.Hub,"math"]);
MathJax.Hub.Queue(function() {
var math = MathJax.Hub.getAllJax("MathDiv")[0];
var i = 1;
setInterval(function() {
MathJax.Hub.Queue(["Text", math, "\\int_0^{" + i + "} x dx"]);
MathJax.Hub.Queue(function() {
displayDiv.innerHTML = mathDiv.innerHTML;
});
i++;
}, 1000);
});
#math {
display: none
}
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<div id="math">$$$$</div>
<div id="display"></div>
I am setting up some basic pagination of a table, and I have the following JS function:
function AddPagination() {
var paginationDiv = document.getElementById("pagination");
for (i = 0; i < 3; ++i) {
var page = document.createElement("a");
page.innerHTML = i + 1;
page.setAttribute("title", i + 1);
page.setAttribute("href", "javascript:RenderResultTable(this.innerHTML)");
paginationDiv.appendChild(page);
}
}
What I want to do is pass page number clicked on to the RenderResultTable method. I have this number stored as the innerHTML and title for the link element, how can I get this passed through using the above code?
Thanks.
Personally, I wouldn't use JavaScript for pagination but if that's the way you want to go, you need to use some string concatenation. I'm not sure what RenderResultTable() does but you can set that line up like this:
page.setAttribute("href", "javascript:RenderResultTable('" + page.innerHTML + "')");
I believe that should do the trick.
EDIT: Shouldn't you be using i++ in your loop instead of ++i? I think what you have right now will give 2 as the first page number. Please correct me if I am wrong.
EDIT: page.innerHTML will need to be escaped by this functions and then unescaped the in the RenderResultTable() function. escape() and unescape(). This is to prevent JavaScript injections and/or accidental bugs.
Okay this is frustrating me to no end. I recently coded a page in JS for a buddy of mine who wants to display wedding pictures to a family to see which ones they'd like to purchase.
I used a for loop to count 1-904:
for (beginnum=1;beginnum<=904;beginnum++) { yada yada...
Then, I used adobe bridge to rename the camera files to be 1-904 and their thumbnails (1-904 + _thumb) and used the loop number to display 904 image spaces, and the correctly numbered picture:
[note:using <) in place of the usual open tag since the site wont display it]
IE...
document.write(beginnum + ":" + "<img src='pictures" + beginnum + "_thumb.jpg' />");
Opera...
document.write("<div>" + beginnum + ":" + "<img src='pictures" + beginnum + "_thumb.jpg' /></div>")
This all works perfectly in IE and Opera (with external CSS modifying the div to not line break).
I then created a function to call up the large version of the picture when clicked on.
The problem is, when I try and nest this function into the JavaScript generated HTML I would need four delimiters. I've heard ''' or """ or the &+numeric; work in some cases as a third and fourth but I can't seem to get them to work... where I run into a problem is here...
[note:again using <) for open tag]
document.write("<a href='javascript:void(0); onClick=
Since I've already used up " and ' I now have nothing left to use to call the function when a picture is clicked.
I usually don't ask for any help, but this time I can't think of anything else that should work... I assume maybe using JS to generate the HTML leaves me with ONLY 2 delimiters that will be recognized by the browser but I am not sure, anyone know for sure? Any fixes anyone can think of?
Thanks,
~Z~
Maybe this will work
for (i=0; i<904;i++)
{
document.write("<div class=\"DivClassName\"><img src=\"pictures_" + i + "thumb.jpg\" onclick=\"OpenAWindowAndDisplayTheBigPhoto(" + i + ")\"></div>");
}
Another approach: Suppose you put everything inside a <DIV id="mainDIV">
var mainDIV = document.getElementByID("mainDIV");
var div, img, a;
for (i=0; i<904; i++)
{
div = document.createElement("DIV");
div.className = "DivClassName";
a = document.createElement("A");
a.href = "javascript:void(0)";
a.onclick = function() {OpenAWindowAndDisplayTheBigPhoto(i);};
img = document.createElement("IMG");
img.src = "pictures_" + i + "thumb.jpg";
mainDIV.appendChild(div);
div.appendChild(a);
a.appendChild(img);
};
Try building the string one piece at a time instead of trying to build the whole literal for the document.write.
Whenever things get too convoluted to follow, just do one part at a time.
var s;
s = "'Hello.' ";
s += '"I must be going."';
Without seeing code it is hard to say for a fact, but you may want to take more advantage of the fact that javascript is a first-class language, so you can create functions and pass them as arguments to other functions, or have functions return functions.
By doing this, you can decompose your page into something that sounds a bit more manageable.
Also, take advantage of the onclick event.
You should be able to simplify the javascript and so avoid this problem, IMO.