How to rotate several strings at one time - javascript

I'm trying to make a webpage. But I have a problem with rotating strings.
I want to make several strings to rotate when the page is loaded.
If there is only one string, it rotates well with this code.
But when there are two or more strings and I give them the same class to rotate with equivalent JavaScript code, it's not working.
It's working(Only the first string)
<body>
<div>
<ul>
<li><span id="div" style="background-color:yellowgreen">
What to eat at Newton Food Centre</span>
</li><p>
<!--<li><span class="div" style="background-color:skyblue">the
most unique cocktails in Singapore</span></li>-->
</ul>
</div>
<script>
var div = document.getElementById("div");
var timer = setInterval("doRotate()",200);
div.onclick = function (e) {
clearInterval(timer);
}
function doRotate() {
var str = div.innerHTML;
var firstChar = str.substr(0,1);
var remains = str.substr(1, str.length-1);
str = remains + firstChar;
div.innerHTML = str;
}
</script>
</body>
and this is not working
<body>
<div>
<ul>
<li><span class="div" style="background-color:yellowgreen">
What to eat at Newton Food Centre</span></li><p>
<li><span class="div" style="background-color:skyblue">
the most unique cocktails in Singapore</span></li>
</ul>
</div>
<script>
var div = document.getElementsByClassName("div");
var timer = setInterval("doRotate()",200);
div.onclick = function (e) {
clearInterval(timer);
}
function doRotate() {
var str = div.innerHTML;
var firstChar = str.substr(0,1);
var remains = str.substr(1, str.length-1);
str = remains + firstChar;
div.innerHTML = str;
}
</script>
</body>
I want to see those two strings are rotating at one time.
Please tell me the error that I'm making...
Thank you!

document.getElementsByClassName("div") will return an object of many divs and not a single div so you need to iterate on them like this :
var div = document.getElementsByClassName("div");
var timer = setInterval("doRotate()", 200);
for (var i = 0; i < div.length; i++) {
div[i].onclick = function(e) {
clearInterval(timer);
}
}
function doRotate() {
for (var i = 0; i < div.length; i++) {
var str = div[i].innerHTML;
var firstChar = str.substr(0, 1);
var remains = str.substr(1, str.length - 1);
str = remains + firstChar;
div[i].innerHTML = str;
}
}
<body>
<div>
<ul>
<li><span class="div" style="background-color:yellowgreen">
What to eat at Newton Food Centre</span></li>
<p>
<li><span class="div" style="background-color:skyblue">
the most unique cocktails in Singapore</span></li>
</ul>
</div>
<script>
</script>
</body>

Related

Word count limit for multiple textarea tags

I have this script to limit the words on a textarea but I want to use the same function to a form that contains multiple textarea tags.
What is the best way to reuse this and make an independent word counter and limiter for every textarea tag in the same form?
Thanks a lot in advance.
var wordLimit = 5;
var words = 0;
var jqContainer = $(".my-container");
var jqElt = $(".my-textarea");
function charLimit()
{
var words = 0;
var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = jqElt.val()[trimmed.length];
jqElt.val(trimmed + lastChar);
}
$('.word-count', jqContainer).text(words);
$('.words-left', jqContainer).text(Math.max(wordLimit-words, 0));
}
jqElt.on("keyup", charLimit);
charLimit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
<textarea class="my-textarea"></textarea>
<span class="words-left"></span> words left
<div>
You can use a generic function ($this) is the textarea element changed.
For relative elements, you can use the function .next(selector)
Also you can read parameters from attributes (maxwords for example).
var jqContainer = $(".my-container");
function charLimit()
{
var words = 0;
var jqElt=$(this);
var wordLimit = jqElt.attr("maxwords");
var words = 0;
var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = jqElt.val()[trimmed.length];
jqElt.val(trimmed + lastChar);
}
jqElt.next('.words-left').text(Math.max(wordLimit-words, 0));
}
$(".my-textarea", jqContainer).on("keyup", charLimit).keyup();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
<textarea id="text1" class="my-textarea" maxwords="5"></textarea>
<span class="words-left"></span> words left
<textarea id="text1" class="my-textarea" maxwords="10"></textarea>
<span class="words-left"></span> words left
<div>
You can wrap your logic up in a function and reuse that function.
See example:
function wordCounter(container, limit) {
var wordLimit = limit;
var jqContainer = $(container);
var jqElt = $("textarea", jqContainer);
function charLimit()
{
var words = 0;
var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = jqElt.val()[trimmed.length];
jqElt.val(trimmed + lastChar);
}
$('.word-count', jqContainer).text(words);
$('.words-left', jqContainer).text(Math.max(wordLimit-words, 0));
}
jqElt.on("keyup", charLimit);
charLimit();
}
wordCounter(".my-container1", 5);
wordCounter(".my-container2", 10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container1">
<textarea class="my-textarea"></textarea>
<span class="words-left"></span> words left
</div>
<div class="my-container2">
<textarea class="my-textarea"></textarea>
<span class="words-left"></span> words left
</div>
Note that you had an issue in your example where the div tag wasn't closed.
if you need to use that same implementation you could add an id to each text area you are going to put in the form, then add an attribute for= to the corresponding spans pointing to the corresponding text area like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
<textarea id="textarea-1" class="my-textarea" onkeyup="charLimit(this)"></textarea>
<span for="textarea-1" class="words-left"></span> words left
<textarea id="textarea-2" class="my-textarea" onkeyup="charLimit(this)"></textarea>
<span class="words-left" for="textarea-2"></span> words left
<div>
var wordLimit = 5;
var words = 0;
var jqContainer = $(".my-container");
function charLimit(elem)
{
var elm = $(elem)
var words = 0;
var wordmatch = elm.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = elm.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = elm.val()[trimmed.length];
elm.val(trimmed + lastChar);
}
$('.word-count', jqContainer).text(words);
$('[for='+ elm.attr('id') +']', jqContainer).text(Math.max(wordLimit-words, 0));
}
This is how I will normally do it:
Create a function that handles the word count refreshMaxWords()
Create a hook that can be tied up with the element <textarea data-max-words="5"></textarea>
(function($) {
var refreshMaxWords = function ($el) {
var wordLimit = parseInt($el.data('max-words')) || false,
wordmatch = $el.val().match(/[^\s]+\s+/g),
words = wordmatch ? wordmatch.length : 0,
// You can change how to get the "words-left" div here
$wordsLeft = $el.parent().find('.words-left');
if (wordLimit !== false) {
if (words > wordLimit) {
var trimmed = $el.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = $el.val()[trimmed.length];
$el.val(trimmed + lastChar);
}
}
if ($wordsLeft.length > 0) {
$wordsLeft.html(Math.max(wordLimit - words, 0));
}
};
$(function () {
$(document).on('keyup.count-words', '[data-max-words]', function (e) {
refreshMaxWords($(this));
});
});
})(jQuery);
This is with assumption of HTML that looks like the following:
<div class="form-group">
<label>Input #1</label>
<textarea class="form-control" data-max-words="5"></textarea>
<p class="help-block"><span class="words-left">5</span> words left.</p>
</div>
<div class="form-group">
<label>Input #2</label>
<textarea class="form-control" data-max-words="10"></textarea>
<p class="help-block"><span class="words-left">10</span> words left.</p>
</div>
The benefits of this approach are:
Cleaner code structure
This can be reused on your other projects.
Notes:
You don't really need to wrap the javascript in
(function($) {
// your code here
})(jQuery);
I like doing it because it ensures that there won't be any conflict by accident.

How to randomly change every character inside the body of a HTML document?

<div id="contents">
<h1>Article I</h1>
<section id="sectionOne">
<p>Hello World</p>
<ul>
<li>Black world</li>
<li>White world</li>
<li>666 world</li>
</ul>
</section>
</div>
<button id="randomText">Random Text</button>
function changeContents() {
var contents = document.getElementById("contents").innerText;
var newContents = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var number = "0123456789";
function isLower(character) {
return character >= "a" && character <= "z";
}
function isUpper(character) {
return character >= "A" && character <= "Z";
}
function isDigit(character) {
return character >= "0" && character <= "9";
}
for (var counter = 0; counter < contents.length; counter++) {
if (isLower(contents.charAt(counter))) {
newContents += alphabet[Math.floor(Math.random() * alphabet.length)];
}
else if (isUpper(contents.charAt(counter))) {
newContents += upperAlphabet[Math.floor(Math.random() * alphabet.length)];
}
else if (isDigit(contents.charAt(counter))) {
newContents += number[Math.floor(Math.random() * alphabet.length)];
}
else {
newContents += contents.charAt(counter);
}
}
for (var counter = 0; counter < contents.length; counter++) {
contents = contents.replace(contents[counter], newContents[counter]);
}
document.getElementById("contents").innerText = contents;
}
I want to create a function that will take every character inside the #contents and change it randomly. The changes should not affect the style. The function is applied to #randomText on click event. How can I write it in plain JavaScript only? I write a pretty bad function here and can't get the work done correctly. Please help...
(function(){
var chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var unfiltered_nodes = document.querySelectorAll('#contents *');
var nodes = [].filter.call(unfiltered_nodes, function(n){ return !n.children.length; });
var btn = document.querySelector('#randomText');
btn.onclick = randomize;
function randomize(){
for(var i = nodes.length-1; i > -1; i--){
var word = nodes[i].innerText;
for(var j = word.length-1; j > -1; j--){
var random_char = getRandomChar();
word = word.replace(word[j], random_char);
}
nodes[i].innerText = word;
}
}
function getRandomChar(){
var len = chars.length-1;
var index = Math.floor(Math.random() * (len));
return chars[index];
}
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body style='padding:5px;'>
<div id="contents">
<h1>Article I</h1>
<section id="sectionOne">
<p>Hello World</p>
<ul>
<li>Black world</li>
<li>White world</li>
<li>666 world</li>
</ul>
</section>
</div>
<button id="randomText">Random Text</button>
</body>
</html>
This should work, it's using the treewalker api, to quickly find all text nodes:
EDIT: Added reset example.
EDIT: Excluded chars not in alphabets.
function getAllTextNodes(node){
var currentNode, nodes = [];
var treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT,
{ acceptNode: function(node) {
if(/\S/.test(node.data)) return NodeFilter.FILTER_ACCEPT;
}}, false);
while(currentNode = treeWalker.nextNode()) nodes.push(currentNode);
return nodes;
}
function randomIndex(array) {
return Math.floor(Math.random() * array.length);
}
function createRandomChar(char) {
var lower = "abcdefghijklmnopqrstuvwxyz";
var upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var number = "0123456789";
if((lower+upper+number).indexOf(char) < 0) return char;
if(!isNaN(parseInt(char))) return number[randomIndex(number)];
if(char === char.toLowerCase()) return lower[randomIndex(lower)];
if(char === char.toUpperCase()) return upper[randomIndex(upper)];
return char;
}
function randomizeContent(selector) {
var element = document.querySelector(selector);
var textNodes = getAllTextNodes(element);
textNodes.forEach(function(node) {
node.textContent = node.textContent.split('').map(function(char) {
return createRandomChar(char);
}).join('');
});
}
// example code
function reset(nodes, originalNodes) {
nodes.forEach(function(node, index) {
node.textContent = originalNodes[index] && originalNodes[index].textContent
});
}
var contentSelector = '#contents';
var contentElement = document.querySelector(contentSelector);
var originalNodes = getAllTextNodes(contentElement).map(function(node) {
return node.cloneNode();
});
document.querySelector('#randomText').addEventListener('click', function(e) {
randomizeContent(contentSelector);
});
document.querySelector('#resetRandomText').addEventListener('click', function(e) {
reset(getAllTextNodes(contentElement), originalNodes);
});
<div id="contents">
<h1>Article I</h1>
<section id="sectionOne">
<p>Hello World</p>
<ul>
<li>Black world</li>
<li>White world</li>
<li>666 world</li>
</ul>
</section>
<section>
<p>
A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine. I am so happy, my dear friend, so absorbed in the exquisite sense of mere tranquil existence, that I neglect my talents.
</p>
</section>
</div>
<button id="randomText">Random Text</button>
<button id="resetRandomText">reset</button>

How to make a list randomizer

I have been working on a fairly pointless website where there are multiple "random" generators. You can check it out here: randomwordgen.net16.net
As you can see there is an unfinished generator at the bottom, that's what I'm here for. I want to get it to generate a list from things you input. My idea is to add the input field's value to the array that will make the list when you hit "Add to List." Then I will have a separate button that will generate the list using that array. The only problem is that I don't know how to add the string to the array when I only know the name of the variable, not the value. If anyone could help me with any of this, that would be great!
This is the code for the whole site:
<!DocType html>
<html>
<head>
<link rel="shortcut icon" href="https://cdn2.iconfinder.com/data/icons/thesquid-ink-40-free-flat-icon-pack/64/rubber-duck-512.png" type="image/x-icon">
<title>Random Word Generator</title>
<style>
body {
background-color:pink;
}
button.10letter {
background-color: blue;
}
button.5letter {
background-color: blue;
position:relative;
top:50px;
}
button.4letter {
background-color: blue;
position:relative;
top:100px;
}
button.3letter {
background-color: blue;
position:relative;
top:150px;
}
button.Add {
position:relative;
top:50px;
}
</style>
</head>
<body>
<h1 style="color:grey">Random word generator:</h1>
<button class="10letter" onclick="doAlert();" style="color:orange">Generate with 10 letters.</button>
<script>
function createRandomWord(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert() {
alert( "Your word is: "+createRandomWord(10)+" (bonus points if your word is real)." );
}
</script>
<button class="5letter" onclick="doAlert5();" style="color:orange">Generate with 5 letters.</button>
<script>
function createRandomWord5(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert5() {
alert( "Your word is: "+createRandomWord(5)+" (bonus points if your word is real)." );
}
</script>
<button class="4letter" onclick="doAlert4();" style="color:orange">Generate with 4 letters.</button>
<script>
function createRandomWord4(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz♀☺☻ƒ=ù"?',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert4() {
alert( "Your word is: "+createRandomWord(4)+" (bonus points if your word is real)." );
}
</script>
<button class="3letter" onclick="doAlert3();" style="color:orange">Generate with 3 letters.</button>
<script>
function createRandomWord3(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert3() {
alert( "Your word is: "+createRandomWord(3)+" (bonus points if your word is real)." );
}
</script>
<h1 style="color:grey">Name Generator:</h1>
<button style="color:orange" onclick="generator();">Generate</button>
<script>
function generator(){
var first = ["Kick","Stupid","Random Name","Officer","School-Related","Unoriginal","Original","Mousey","Website to name things?","n00b","Error","var first=name.first","Bob","Joe","Boris","Duck","Cheese","Pablo","Stimuli","Last Test Grade","First Word","Puss","Cat","Cherokee", "Jerry", "[Insert Weird First Name Here]"]
var last = ["Me","Idiot","dummy.dummy","randomwordgen.net16.net (shameless advertising)","he went that way","it was him!","DESTRUCTION...","Rats","You need advice for a name, use a website or something! Oh wait.","Opposition","Apple","404 not found","var last=name.last","You sure you want to pick this name?","McGuire","Rox","Knox","Bobert","Green","Raul","Damend","Milk","Positive","Negative","Rocky","Boots","Cherry","Parakeet","[Insert Weird Last Name Here]"]
var randomNumber1 = parseInt(Math.random() * first.length);
var randomNumber2 = parseInt(Math.random() * last.length);
var name = first[randomNumber1] + " " + last[randomNumber2];
alert(name);
}
</script>
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
</body>
</html>
And this is the code for the list part:
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
Thanks in advance!
Here is an example in which we take the input value, add it to an array, shuffle the array and then put it in a list <ul>. Every added value is added to the array and re-shuffles the list.
Try this:
EDIT
I added the shuffle function for when you just want to shuffle without adding new values.
var randomList = [];
function appendToArray() {
var word = document.getElementById("Words").value;
randomList.push(word);
updateList(randomList);
document.getElementById("Words").value = "";
}
function updateList(wordsArr) {
shuffleArr(wordsArr);
var list = document.getElementById('list');
list.innerHTML = "";
for (var i =0; i < wordsArr.length; i++) {
var word = wordsArr[i];
var li = document.createElement('li');
li.innerText = word;
list.appendChild(li);
}
}
function shuffleArr(arr) {
var j,
x,
i;
for (var i = arr.length; i; i--) {
j = Math.floor(Math.random() * i);
x = arr[i - 1];
arr[i - 1] = arr[j];
arr[j] = x;
}
}
function shuffleList() {
var list = randomList;
updateList(list);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Shuffle" onClick="shuffleList()">Shuffle List</button>
<h3>List</h3>
<ul id="list"></ul>
You will need to make your array variable global so you can access it from multiple functions:
// declare this only once
var arr = [];
function appendToArray() {
var word = document.getElementById("Words").value;
// check to make sure something was entered
if (word && word.length) {
arr.push(word);
// clear the input box if added to the array
document.getElementById("Words").value = '';
}
}
Then you can have another function that picks whatever you need out of the array, which is now accessible because we moved it to the global scope of your document. You could have another button to empty the array then as well.
Is this what are you looking for?
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
function showArray() {
console.log(arr);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Add" onClick="showArray()">Show List</button>
</div>
Initialize array outside the function. Otherwise you are making it empty every time you call the function.
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
</script>
</div>

Making a javascript hangman game and I can't get my function to apply to repeated letters

Everything about the script works great right now unless there's a repeated letter in the word. If so, then it will only display the first of the letters. For example, if the random word is "look" it would display like this "lo k".
Unfortunately the only other related javascript hangman question here was for a script that didn't actually have issues on repeated letters. For reference: how to deal with repeated letters in a javascript hangman game. Can anyone help me get through the repeated letter issue? Thanks!
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-1.11.2.min.js"></script>
<script src="js/jquery-1.11.2.js"></script>
<link rel="stylesheet" href="css/main.css">
<title>Hang a Blue Devil</title>
</head>
<body>
<div class="wrapper">
<h1 class="title">Hangman</h1>
<h2 class="attempt-title">You have this many attempts left: </h2>
<ul class="hangman-word">
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
</ul>
<h3 class="hangman-letters"></h3>
<input class="text-value" type="text" maxlength="1" onchange="setGuess(this.value)">
<button class="text-button" onclick="checkGuess()"></button>
<p class="letters-guessed"></p>
</div>
</body>
<script src="js/hangman.js"></script>
</html>
My JS:
var hangmanWords = [
"the","of","and","a","to","in","is","you","that","it","he",
"was","for","on","are","as","with","his","they","I","at","be",
"this","have","from","or","one","had","by","word","but","not",
"what","all","were","we","when","your","can","said","there",
"use","an","each","which","she","do","how","their","if","will",
"up","other","about","out","many","then","them","these","so",
"some","her","would","make","like","him","into","time","has",
"look","two","more","write","go","see","number","no","way",
"could","people","my","than","first","water","been","call",
"who","oil","its","now","find","long","down","day","did","get",
"come","made","may","part"
];
// declared variables
var randomNumber = Math.floor(Math.random() * 100);
var randomWord = hangmanWords[randomNumber];
var underscoreCount = randomWord.length;
var underscoreArr = [];
var counter = randomWord.length +3;
var numberTest = 0;
var lettersGuessedArr = [];
var lettersGuessedClass = document.querySelector('.letters-guessed');
var li = document.getElementsByClassName('tester');
var textValue = document.querySelector('.text-value');
var attemptTitle = document.querySelector('.attempt-title');
var hangmanWordClass = document.querySelector('.hangman-word');
var hangmanLettersClass = document.querySelector('.hangman-letters');
// actions
attemptTitle.innerHTML = "You have this many attempts left: " + counter;
console.log(randomWord);
function setGuess(guess) {
personGuess = guess;
}
for (i=0;i<underscoreCount;i+=1) {
underscoreArr.push("_ ");
underscoreArr.join(" ");
var underscoreArrString = underscoreArr.toString();
var underscoreArrEdited = underscoreArrString.replace(/,/g," ");
hangmanLettersClass.innerHTML = underscoreArrEdited;
}
function pushGuess () {
lettersGuessedArr.push(personGuess);
var lettersGuessedArrString = lettersGuessedArr.toString();
var lettersGuessedArrEdited = lettersGuessedArrString.replace(/,/g," ");
lettersGuessedClass.innerHTML = lettersGuessedArrEdited;
}
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
i += 20;
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
};
My bin:
http://jsbin.com/dawewiyipe/4/edit
You had a stray bit of code that didn't belong:
i += 20;
I took it out, and the problem went away (the loop was intended to check each character, the +=20 broke the process of checking each character)
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
}
http://jsbin.com/noxiqefaji/1/edit

an unordered list from Array items using innerHTML in Javascript

I am trying to add a bulleted list to the page after the user enters 'exit' into a prompt; the list should not include the term 'exit'. I was able to get the list in full using document.write but this included the 'exit' and got rid of my page formatting. I am pretty sure I need to use innerHTML, but when I do this all I get is the page without any of the array items. Any help is greatly appreciated.
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script>
function askMe() {
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit'){
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
var MyList = getElementById('results');
MyList.innerHTML = "<li>"+list+"</li>";
}
}
</script>
</head>
<body onload="askMe()">
<ul>
<div id="results">
</div>
</ul>
<br/>
<br/>
</body>
you have to use document.getElementById() and also generate a string inside the loop and use inner html after the loop so that the previous li's dont get over written.
update the code portions like
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
and in html , remove the div inside ul and giv id to ul
<ul id="results">
</ul>
and here is the full code becomes:
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script type="text/javascript">
function askMe()
{
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit')
{
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++)
{
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
}
</script>
</head>
<body onload="askMe()">
<ul id="results">
</ul>
<br/>
<br/>
</body>
</html>
You should use MyList.innerHTML += "<li>"+list+"</li>"; (notice the use of += instead of =)
Also, change your <ul> HTML to be:
...
<ul id="results">
</ul>
...

Categories

Resources