using Javascript how to display element one by one on click - javascript

how to display element one by one on click using only Javascript, in my example when I click all elements show at once, but i need only one click - one element. I appreciate if you show the simplest way to do if in order to i can understand how it works
$(function() {
var cars = ["audi", "bmw", "volvo"];
var x = "";
var i;
for (i = 0; i <cars.length; i++) {
x += cars[i] + "<br>";
}
document.getElementById("btn").onclick = function() {
document.getElementById("text").innerHTML = x;
}
});

You may update your code as follows. At the very beginnig, your are initializing x with empty string. Then for each click on button, append an element from array with new line tag.
var cars = ["audi", "bmw", "volvo"];
var x = "";
var i = 0;
document.getElementById("btn").onclick = function() {
if( i < cars.length) {
x += cars[i++] + "<br>";
}
document.getElementById("text").innerHTML = x;
}
<p id="text"></p>
<button id="btn">Result</button>

<html>
<script>
var cars = ["audi", "bmw", "volvo"];
var x = "";
var count = 0;
function appendArray(){
if(count<cars.length){
x += cars[count]+ "<br>";
document.getElementById("appendText").innerHTML = x;
count++;
}else{
count = 0;
document.getElementById("appendText").innerHTML = "";
}
}
</script>
<p id="appendText"></p>
<button onclick="appendArray()">Submit</button>
</html>

Here is one solution in vanilla javascript:
var button = document.getElementsByTagName('button')[0];
var i = 0;
function addCar(i) {
var cars = ['audi', 'bmw', 'volvo'];
var paragraph = document.getElementsByTagName('p')[0];
if (i < cars.length) {
var newLine = document.createElement('br');
var newCar = document.createTextNode(cars[i]);
paragraph.appendChild(newLine);
paragraph.appendChild(newCar);
}
}
button.addEventListener('click',function(){addCar(i); i++;},false);
<p></p>
<button>Click for a New Car</button>

Related

JS, a way to have a button refresh the result and print it on the page

<script>
function makeid() {
var text = "";
var char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < l; i++) {
text += char_list.charAt(Math.floor(Math.random() * char_list.length));
}
return text;
}
console.log(makeid(8));
makeid(8);
document.write(makeid());
</script>
Hey, guys. I have this code currently in my HTML, I'm wondering how I can have the output of this code printed on the page and then refreshed everytime I click an HTML button. If you have any questions I'll try to answer them best I can.
This worked for me
<div id="content"></div>
<button id="myBtn"></button>
<script>
var btn = document.getElementById('myBtn');
var content = document.getElementById('content');
btn.onclick = function(){
function makeid(l) {
var text = "";
var char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < l; i++) {
text += char_list.charAt(Math.floor(Math.random() * char_list.length));
}
return text;
}
console.log(makeid(8));
var id = makeid(8);
content.innerHTML = id;
}
</script>
Everytime the button is clicked, your function will be triggered and the generated Id will be put inside the <div id="content"></div>
Here is the codepen for testing

Counter Using Javascript, HTML & CSS Not Working

Can anyone help me to get this (https://jsfiddle.net/hmatrix/v3jncqac/) code to work?
Inentention: I want to create a counter that increases in increments.
My HTML:
<body onload="incrementCount(10)">
<div class="main_container" id="id_main_container">
<div class="container_inner" id="display_div_id">
</div>
</div>
</body>
My JS:
var counter_list = [10,10000,10000];
var str_counter_0 = counter_list[0];
var str_counter_1 = counter_list[1];
var str_counter_2 = counter_list[2];
var display_str = "";
var display_div = document.getElementById("display_div_id");
function incrementCount(current_count){
setInterval(function(){
// clear count
while (display_div.hasChildNodes()) {
display_div.removeChild(display_div.lastChild);
}
str_counter_0++;
if (str_counter_0 > 99) {
str_counter_0 = 0; // reset count
str_counter_1++; // increase next count
}
if(str_counter_1>99999){
str_counter_2++;
}
display_str = str_counter_2.toString() + str_counter_1.toString() + str_counter_0.toString();
for (var i = 0; i < display_str.length; i++) {
var new_span = document.createElement('span');
new_span.className = 'num_tiles';
new_span.innerText = display_str[i];
display_div.appendChild(new_span);
}
},1000);
}
<body onload="incrementCount(10)">
<div class="main_container" id="id_main_container">
<div class="container_inner" id="display_div_id">
</div>
</div>
</body>
<script>
var counter_list = [10,10000,10000];
var str_counter_0 = counter_list[0];
var str_counter_1 = counter_list[1];
var str_counter_2 = counter_list[2];
var display_str = "";
var display_div = document.getElementById("display_div_id");
function incrementCount(current_count){
setInterval(function(){
// clear count
while (display_div.hasChildNodes()) {
display_div.removeChild(display_div.lastChild);
}
str_counter_0++;
if (str_counter_0 > 99) {
str_counter_0 = 0; // reset count
str_counter_1++; // increase next count
}
if(str_counter_1>99999){
str_counter_2++;
}
display_str = str_counter_2.toString() + str_counter_1.toString() +
str_counter_0.toString();
for (var i = 0; i < display_str.length; i++) {
var new_span = document.createElement('span');
new_span.className = 'num_tiles';
new_span.innerText = display_str[i];
display_div.appendChild(new_span);
}
},1000);
}
</script>
JSFIDDLE: https://jsfiddle.net/v3jncqac/32/
Your onload function cannot find the function because your js is in a different file. you need to add script src on top of html or do it as shown above.

Why does this for loop not display in my div using JavaScript?

I want to display the content in my div but the code won't work. Please show me how to do it.
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for (i = 0; i < 11; i++) {
var disp = "the number is " + i;
console.log(disp);
}
disp = document.getElementById("display").innerHTML;
</script>
</body>
</html>
How can I get the loop to display my variable in my selected div? Which part of my code is wrong? please help.
Tehre are multiple problems
<p id="display"></p>
<script>
var i;
//initialize the value
var disp = '';
for (i = 0; i < 11; i++) {
//concatenate the value of disp so that new value will be added to the previous content other wise the values will be overwritten
disp += "the number is " + i;
console.log(disp);
}
//assign value of disp to the elemet innerHTML
document.getElementById("display").innerHTML = disp;
</script>
Set the innerHTML inside the for loop.
for (var i = 0; i < 11; i++) {
var disp = "the number is " + i;
document.getElementById("display").innerHTML = disp;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
IF you want to display all the content at once
var disp = ''; // Assign empty string
for (var i = 0; i < 11; i++) {
disp += " the number is " + i; // Concat message
}
document.getElementById("display").innerHTML = disp; // Add into html
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Because you never write anything to your HTML page. You just display it in your console. And later you assign the HTML content of the #display element to the variable disp, which doesn't make any sense:
disp = document.getElementById("display").innerHTML;
This is how it will work
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
// This just writes to the javascript console
console.log(disp);
// This writes in the #display element on your page
document.getElementById("display").innerHTML += disp + '<br>';
}
</script>
</body>
</html>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
console.log(disp);
}
document.getElementById("display").innerHTML = disp;
Something like this should be fine
function createDivs(){
var pContainer = document.getElementById("display");
var i;
for(i = 0; i < 11; i++){
var message = "the number is " + i;
console.log(message);
var element = document.createElement("div");
element.innerHTML = message;
pContainer.appendChild(element);
}
disp = document.getElementById("display").innerHTML;
};
createDivs();

How can I remove unwanted piece of HTML markup on the page?

I have trouble with this piece of code. When I click it once, all is good and the behavior is as designed , but when I click it more than once, then there is all bunch of HTML that appears in the div (text area). How should I revise my JS to make it not happen?
HTML :
<div id="transcriptText">Lorem ipsum dolor sit amet </div>
<br>
<div id="divideTranscript" class="button"> Transform the Transcript! </div>
JS :
window.onload = function() {
var transcriptText = document.getElementById("transcriptText");
var newTranscript = document.createElement("div");
var divideTranscript = document.getElementById("divideTranscript");
divideTranscript.onclick = EventHandler;
function EventHandler() {
changeText();
}
function changeText() {
var sArr = transcriptText.innerHTML.split(" ");
transcriptText.innerHTML = "";
console.log(sArr);
var count = 0;
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.id = "word" + i;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
newSpan.onmouseover = mouseOverFunction;
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
newSpan.onmouseout = mouseOutFunction;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
transcriptText.appendChild(newSpan);
count++;
};
}
};
Here is it live http://jsfiddle.net/b94DG/1/
The main problem is that you use the innerHTML property instead of the .textContent property each time.
Here is an improved version of changeText() that doesn't matter how many times you run it:
function changeText() {
var sArr = transcriptText.textContent.split(/\s+/g); // changed
transcriptText.innerHTML = "";
var count = 0;
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
if (!item) continue; // changed: don't add spans for empty strings
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.id = "word" + i;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
newSpan.onmouseover = mouseOverFunction;
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
newSpan.onmouseout = mouseOutFunction;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
transcriptText.appendChild(newSpan);
count++;
};
}

Adding select boxes dynamically

I have made a simple dynamic form to generate input boxes.
<body>
<div id="main1">
<input type="button" onclick="addSelectBox ()" name="clickme" value="+"/>
<input type="button" onclick="removeSelect();" value="-"/>
<input type="button" onclick="xmlData();" value="XML" />
</div>
<div id="main">
</div>
</body>
Here's the javascript code:
(function () {
var selele=0;
var brindex=0;
function addSelectBox() {
selele = selele + 1;
var spantag = document.createElement("span");
spantag.setAttribute("id", selele);
var parentDiv = document.getElementById("main");
var selectElement = document.createElement("select");
var selectElement1 = document.createElement("select");
var selectElement2 = document.createElement("select");
var selectElement3 = document.createElement("select");
var arr = new Array("Stocks", "MutualFunds");
var arr2 = new Array("individual", "401k", "IRA");
var arr3 = new Array("contains", "equals");
var arr4 = new Array("scrapedaccounttype", "scrapedtransactiontype");
var textbox = document.createElement('input');
for (var i = 0; i < arr.length; i++) {
var option = new Option(arr[i]);
selectElement.options[selectElement.options.length] = option;
}
for (var i = 0; i < arr2.length; i++) {
var option = new Option(arr2[i]);
selectElement1.options[selectElement1.options.length] = option;
}
for (var i = 0; i < arr3.length; i++) {
var option = new Option(arr3[i]);
selectElement2.options[selectElement2.options.length] = option;
}
for (var i = 0; i < arr4.length; i++) {
var option = new Option(arr4[i]);
selectElement3.options[selectElement3.options.length] = option;
}
spantag.appendChild(selectElement);
spantag.appendChild(selectElement1);
spantag.appendChild(selectElement2);
spantag.appendChild(selectElement3);
spantag.appendChild(textbox);
parentDiv.appendChild(spantag);
linebreak();
};
function removeSelect() {
var parentDiv = document.getElementById("main");
var removetg = document.getElementById(selele);
if (selele != 1) {
parentDiv.removeChild(removetg);
selele = selele - 1;
} else {
parentDiv.removeChild(removetg);
parentDiv.innerHTML = "";
selele = selele - 1;
}
removeBreak();
};
function linebreak() {
brindex = brindex + 1;
var brtag = document.createElement("br");
brtag.setAttribute("id", brindex);
var parentDiv = document.getElementById("main");
parentDiv.appendChild(brtag);
};
function linespace() {
var myElement = document.createElement("span");
myElement.innerHTML = "&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp";
var parentDiv = document.getElementById("main");
parentDiv.appendChild(myElement);
};
function removeBreak() {
var myElement = document.getElementById(brindex);
var parentDiv = document.getElementById("main");
brindex = brindex - 1;
parentDiv.removeChild(myElement);
};
function xmlData() {
xmlDoc = loadXMLDoc("data.xml");
newel = xmlDoc.createElement("edition");
x = xmlDoc.getElementsByTagName("span")[0];
x.appendChild(newel);
};
});
I can't get it to work on jsFiddle, the buttons don't work.
They work fine if I embed it in a tag.
Can anybody help me fix them.
EDIT: I guess i added anonymously because I wanted the var selele and brindex globally for all these functions.
I have made the code changes.
JSFIDDLE
Your functions are within an anonymous function and thus not available from outside.
First remove the code from the anonymous function (see here: http://jsfiddle.net/uH84W/6/), then fix the console errors you get (I assume that's not the whole code).
function addSelectBox() {...
In your fiddle you select onload but you change onload to no warp-in or no warp-in now it's work fine

Categories

Resources