I'm missing some little thing.. prints the array but doesn't wait in between lines.
<script type="text/javascript">
function showLines()
{
arr =
[
"Hi!",
"Welcome!",
"Hello!"
]
var duration=2000;
document.getElementById("quotes").innerHTML=arr;
setTimeout('showLines()',duration);
}
</script>
That's because your just printing out the whole array, try this.
function showLines(_index) {
var arr =["Hi!", "Welcome!", "Hello!"], html = '', i, index = _index || 0,
newIndex;
for (i = 0; i < index && i < arr.length; ++i) {
html += arr[i] + "<br />";
}
document.getElementById("quotes").innerHTML=html;
newIndex = index + 1;
if (newIndex < arr.length) {
setTimeout(function() {showLines(newIndex);}, 2000);
}
}
That should do the trick.
If you only want one at a time then replace
for (i = 0; i < index && i < arr.length; ++i) {
html += arr[i] + "<br />";
}
with
document.getElementById("quotes").innerHTML=arr[index];
The line
document.getElementById("quotes").innerHTML=arr;
will convert arr into a String by joining it with commas. Therefore, you will see
Hi!, Welcome!, Hello!
This function is idempotent, which is probably not what you are going for. I think what you're missing is an index that lets you know which element of the array you are on the next time the function is executed, and replaces the content of the quotes element with the next item in the array.
Most answers here are re initializing your array on each iteration.It makes no sense to do that. You should do it like this:
<script type="text/javascript">
function showLines(){
var arr =
[
"Hi!",
"Welcome!",
"Hello!"
], i = 0;
(function showLinesHelper(){
document.getElementById("quotes").innerHTML += arr[i++]+'<br />';
if(i < arr.length)
setTimeout(showLinesHelper, 2000);
})();
}
</script>
This way it works, and your array, and i are only initialized once.
EDIT In response to comment:
<script type="text/javascript">
function showLines(){
var arr =
[["Hi!", 3000],
["Welcome!", 500],
["Hello!", 1000]]
, i = 0;
function showLinesHelper(){
document.getElementById("quotes").innerHTML += arr[i++][0]+'<br />';
if(i < arr.length)
setTimeout(showLinesHelper, arr[i][1]);
}
setTimeout(showLinesHelper, arr[0][1]);
}
</script>
You never asked him to wait. You're just calling the same function every 2 seconds.
Try with showLines(i), innerHTML += arr[i], and setTimeout(showLines,duration,i++)
<script type="text/javascript">
function showLines(i)
{
arr =
[
"Hi!",
"Welcome!",
"Hello!"
]
var duration=2000;
document.getElementById("quotes").innerHTML += arr[i];
i++;
setTimeout(showLines,duration,i);
}
</script>
First of all, you should wrap your code in an onload or domready function. jQuery is good at this. You should use window.onload = myfunc; to do this.
Your code should look like this:
<script type="text/javascript">
var init = function () {
var myarray = ["Hi!","Welcome!","Hello!"], index = 0, printline = function () {
document.getElementById("quotes").innerHTML += myarray[index];
if (index + 1 < myarray.length) {
setTimeout(printline, 2000);
}
index++;
};
printline();
}
window.onload = init;
</script>
Related
This function organize list, not organized in alphabetical order: ascending/descending in Firefox and Internet Explorer.
In google chrome and Edge is working.
Here is code:
<script type="text/javascript">
window.onload = function () {
var desc = false;
document.getElementById("Order").onclick = function () {
sortUnorderedList("PostList", desc);
desc = !desc;
return false;
}
}
function compareText(a1, a2) {
var t1 = a1.innerText,
t2 = a2.innerText;
return t1 > t2 ? 1 : (t1 < t2 ? -1 : 0);
}
function sortUnorderedList(ul, sortDescending) {
if (typeof ul == "string") {
ul = document.getElementById(ul);
}
var lis = ul.getElementsByTagName("li");
var vals = [];
for (var i = 0, l = lis.length; i < l; i++) {
vals.push(lis[i]);
}
vals.sort(compareText);
if (sortDescending) {
vals.reverse();
}
ul.innerHTML = '';
for (var i = 0, l = vals.length; i < l; i++) {
ul.appendChild(vals[i]);
}
}
</script>
Try this:
document.getElementById("hello").onclick = talk;
function talk()
{
alert('It works!');
}
<a id="hello">Click me!</a>
It seems to be right. Is your element ID right? Check if you have more then one element using the same ID also. If you can, post you HTML code.
It's bad if you use code of unknown source, you might even get in trouble with copyrights! Here is a simplified version (No, I won't apologize for the use of Bubble-sort!) that should be easy to follow.
Edited on request of OP to add an example of deep copying
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
// as shown in http://stackoverflow.com/questions/3066427/copy-all-childnodes-to-an-other-element-in-javascript-native-way
function copyElements (dst,src){
while (src.hasChildNodes()) {
dst.appendChild(src.removeChild(src.firstChild))
}
}
function sortUnorderedList(element_id, direction){
var table = document.getElementById(element_id);
var rows,i,tmp;
// get the rows in the order as they are
rows = table.rows;
i = rows.length - 1;
// tmp must be a node for this highly simplified stuff to work
tmp = document.createElement("getoffmylawn");
// do a simple Bubble sort (sorts lexically, maybe not what you want!)
// Assumes things to sort are in the first cell, adjust if necessary
for(; i > 0; i--){
for(j = 0;j < i; j++){
if(direction === false){
if(rows[j].firstChild.firstChild.textContent < rows[j+1].firstChild.firstChild.textContent){
copyElements (tmp , rows[j]);
copyElements (rows[j] , rows[j+1]);
copyElements (rows[j+1] , tmp);
}
}
else{
if(rows[j].firstChild.firstChild.textContent > rows[j+1].firstChild.firstChild.textContent){
copyElements ( tmp , rows[j]);
copyElements (rows[j] , rows[j+1]);
copyElements (rows[j+1] , tmp);
}
}
}
}
}
window.onload = function () {
var desc = false;
document.getElementById("Order").onclick = function () {
sortUnorderedList("FileList", desc);
desc = !desc;
return false;
};
};
</script>
</head>
<body>
<table id="FileList">
<tr><td>Foo</td></tr>
<tr><td>Bar</td></tr>
<tr><td>Foobar</td></tr>
<tr><td>Something</td></tr>
<tr><td>Anything</td></tr>
<tr><td>Somehwere</td></tr>
<tr><td>elsewhere</td></tr>
<tr><td>completely lost</td></tr>
</table>
<button id="Order">Sort</button>
</body>
</html>
If you think the order is wrong you have found out what "lexical order" actually means.
To work in Internet Explorer and Firefox, I replaced:
innerText to textContent
I'm new to JS and would like to know how to refactor this simple code so that I can pass in strings to count the number of "e" in a string.
function countE() {
var count = 0;
var str = "eee";
var charLength = str.length;
for (i =0; i <= charLength; i++){
if(str.charAt(i) == "e"){
count++;
}
}
console.log(count);
}
I would like to execute this function where I can do something like this:
countE('excellent elephants');
which would log 5.
function countE(str) {
if(typeof(str)==='undefined') str = 'eee';
var count = 0;
var charLength = str.length;
for (i =0; i <= charLength; i++){
if(str.charAt(i) == "e"){
count++;
}
}
console.log(count);
}
If you want to make your function body shorter, you can do the following:
function countE(str) {
return str.match(/e/g).length;
}
And even more sophisticated:
function count(what) {
return function(str) {
return str.match(new RegExp(what, 'g')).length;
};
}
// now you can do the this
var countE = count('e');
var resultE = countE('excellent elephants');
var countL = count('l');
var resultL = countL('excellent elephants');
If I understand your comment correctly, you want to do something like this:
function countE(inString) {
var count = 0;
var str = inString ? inString : "eee";
var charLength = str.length;
for (i =0; i <= charLength; i++){
if(str.charAt(i) == "e"){
count++;
}
}
console.log(count);
}
You can also use a regular expression
function countE(str) {
var count = str.match(/e/g).length;
console.log(count);
}
or
function countE(str) {
console.log(str.match(/e/g).length);
}
I have this code who works properly with for loop, how to made while and do/while loop to work properly on same way when i click on button?
<body>
<div>
<button onclick = "fun()">Click
</button>
<p id = "dr">
</p>
<script>
function fun() {
var str = "";
for (var i = 0; i < 11; i++) {
str = str + i + "<br/>";
document.getElementById("dr").innerHTML = str;
}
}
</script>
</div>
</body>
This sounds a bit like HW, so I won't give you the entire code.
However, you have this code in your for loop
for (var i=0; I<11; i++)
}
In that, I is never defined, so you should probably change it to i.
For changing it to a do{}..while() loop, remember that every for loop of the form for(a;b;c){d;} can be expanded to the while loop
a;
while(b){
d;
c;
}
and therefore to the do..while loop of
a;
do{
d;
c;
}while(b);
while:
function fun()
{
var str ="";
while( i < 11 )
{
str=str + i +"<br/>";
document.getElementById("dr").innerHTML =srt;
i++;
}
}
do/while:
function fun()
{
var str ="";
do
{
str=str + i +"<br/>";
document.getElementById("dr").innerHTML =srt;
i++;
}while( i < 11 );
}
I have a list of question in my javascript file. Each question has a question number and question description and options. A question can be added anywhere in the list of questions. So if a question is added into the top of all questions, then i need to change the question numbers of all the below ones. How can achieve this. Can i use javascript for this?
I would suggest using an <ol> for each question, and let the page handle reflowing the numbers.
Otherwise you'll need to set a target number before inserting, and for each element in the list you'll check to see if it's number is greater than the target, and then if so increment the number by one.
var Target = //new number that I want the inserted question to be
foreach (element in list) {
if (element.Number > Target) element.Number += 1;
}
list.add( //new question with # set to Target );
This works.
<ol id="questions_list"></ol>
var questions = ["A foo walks into a bar. What happens?", "Why did foo cross the road?"];
addQuestion("foo", 1);
function addQuestion(question, position)
{
if(position > 0 && position < questions.length)
{
var firstHalf = questions.slice(0, position);
var secondHalf = questions.slice(position, questions.length);
firstHalf.push(question);
questions = firstHalf.concat(secondHalf);
console.log("slice");
}else if(position <= 0)
{
questions.unshift(question);
console.log("beginning");
}else if(position >= questions.length)
{
questions.push(question);
console.log("end");
}
updateQuestionList();
}
function updateQuestionList()
{
var questions_list = document.getElementById("questions_list");
questions_list.innerHTML = "";
for(var i=0;i<questions.length;i++)
{
var question = document.createElement("LI");
question.innerHTML = questions[i];
questions_list.appendChild(question);
}
}
http://jsfiddle.net/jPxwW/1/
Array prototype ( fun! =) ):
// zero-based insert
Array.prototype.insert = function(index, item) {
var i = 0, list = [];
if (this.length == index) {
list = this;
list.push(item);
return list;
}
for(; i < this.length; i++) {
if (index == list.length) {
list.push(item);
i--;
} else {
list.push(this[i]);
}
}
return list;
};
Array.prototype.print = function (base) {
base = base || 1;
for (var i = 0, out = []; i < this.length; i++) {
out.push((base + i) + '. ' + this[i]);
}
return out.join("\n");
};
list = ['when?', 'where?', 'why?'];
list = list.insert(0, 'who?'); // first: ["who?", "when?", "where?", "why?"]
list = list.insert(3, 'how?'); // 4th: ["who?", "when?", "where?", "how?", "why?"]
list = list.insert(list.length, 'last?'); // last: ["who?", "when?", "where?", "how?", "why?", "last?"];
list.print();
/**
"1. who?
2. when?
3. where?
4. how?
5. why?
6. last?"
**/
You could do something like this using ordered lists (ol) and jQuery:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type ="text/javascript">
$(function(){
var n = 2;
$('button').delegate('click', function(){
$(this).parents('li').after('<li><p><span>Question'+n+'</span><button>Create new question</button></p></li>');
n += 1;
})
})
</script>
</head>
<body>
<ol>
<li>
<p><span>Question 1</span><button>Create new question</button></p>
</li>
</ol>
</body>
</html>
The code below works and is good but I am going to place it into a DRUPAL page and I would like it to refresh the "DIV" instead of the whole page. Can someone help? Thanks!
document.write("<div class='box1'><center><h1>Telling Time Worksheets</h1></center><div class='box_number_holder'>")
var nums = [01,02,03,04,05,06,07,08,09,10,11,12];
var gen_nums = [];
function in_array(array, el) {
for(var i = 0, j = array.length; i < j; i++)
if(array[i] == el) return true;
return false;
}
function get_rand(array) {
var rand = array[Math.floor(Math.random()*array.length)];
if(!in_array(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return get_rand(array);
}
for(var i = 0; i < 9; i++) {
document.write("<div class='box_numbers'><center>What Time is it?" + get_rand(nums) + "</center></div>");
}
Thanks!
Create a function that loops through all of your dynamically created div elements:
function refreshDivs() {
$('.box_numbers > center').each(function() {
$(this).html('What Time is it? ' + get_rand(nums));
});
}