How to apply class function on id function? - javascript

So I have a task to make function (show/hide) for every paragraph (five of them) and I did like so
function btn() {
var x = document.getElementById('para');
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
For every paragraph I used Id instead of class. Because task said one button per one paragraph.
Now I have a problem how to apply this (color) function for all of them in the same time.
function color() {
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
elements = document.getElementByClassName('color');
for (var i = 0; i < elements.length; i++) {
document.getElementByClassName('color')[i].style.backgroundColor = bgColorCode;
}
}
//Html
<button onclick = "color()">Color</button>
<button onclick = "btn()">Show/Hide</button>
<p id = "para"> Example 1 </p>
<button onclick = "btn2()">Show/Hide</button>
<p id = "para2"> Example 2 </p>
...
Idk how to apply this function "color" to all of my paragraphs because they are under id?
Any solutions?

If you add the class color to your para elements and change the function getElementByClassName() to getElementsByClassName() (you forgot an s). then your code works. Within the for loop you can use the elements array elements[i] instead of another call to the getElementsByClassName() function.
function color() {
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
elements = document.getElementsByClassName('color');
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = bgColorCode;
}
}
//just slightly modified so it works with multiple paragraphs by making the id a function parameter.
function btn(id) {
var x = document.getElementById(id);
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="color()">Color</button>
<button onclick="btn('para')">Show/Hide</button>
<p class="color" id="para">Example 1</p>
<button onclick="btn('para2')">Show/Hide</button>
<p class="color" id="para2">Example 2</p>

Hope this is what you want. Tell me if you have doubts.
The function toggleshow(htmlObj) selects next element sibling of element which triggered the function with an argument this which represent the current HTMLelement and if the value of style.display is set to none, then it changes it value to block else change it to none.
see HTML DOM manipulation
The second function color() takes advanced parameters that is (string)id of HTML element, and loops through all arguments passed and change bgcolor for every id. You can pass many arguments as you want.
see this
document.querySelector('css selector') selects first html element using css selectors
function toggleshow(htmlObj){
var par = htmlObj.nextElementSibling;
if(par.style.display !== 'none'){
par.style.display = 'none';
}else{
par.style.display = 'block';
}
}
function color(){
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
for (var i = 0; i < arguments.length; i++) {
document.querySelector('#'+arguments[i]).style.backgroundColor = bgColorCode;
}
}
button{
display:block
}
<button onclick = "color('para', 'para2', 'para3', 'para4', 'para5')">Color</button>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para"> Example 1 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para2"> Example 2 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para3"> Example 2 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para4"> Example 2 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para5"> Example 2 </p>
*sorry for my bad English and spelling mistakes.

A better and more dynamic solutions with JQUERY:
*If you don't know how to use Jquery then you can check Mark Baijens answer.
function btn(e) {
if ($(e).next().css('display') == "none") {
$(e).next().show()
$(e).html("Hide")
} else {
$(e).next().hide()
$(e).html("Show")
}
}
function color() {
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
//elements = document.getElementByClassName('color');
$(".para").css("background-color",bgColorCode)
}
<div>
<button onclick = "color()">Color</button>
</div>
<hr>
<div id="wrapper">
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 1 </p>
<hr>
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 2 </p>
<hr>
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 3 </p>
<hr>
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 4 </p>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

Related

not able to use animation for typing game

I was trying to build a game, but I am not able to setInterval properly. The word is not getting printed on the screen when I click on the start game button, after 5seconds it directly shows GAME OVER.
var btn= document.querySelector('#btn');
btn.addEventListener("click", myMove);
function myMove() {
var word = document.querySelector('#word');
var input=document.querySelector('#written');
var words=['xylophone', 'cat', 'bat', 'chollima'];
var i=0;
var id = setInterval(frame, 5000);
function frame() {
word.innerHTML=words[i];
i = (i < 3) ?( i+1) : 0;
if (input.innerHTML== word.innerHTML) {
clearInterval(id);
} else {
word.innerHTML='GAME OVER';
}
}
}
<div id="heading">TYPING GAME</div>
<label>
<div id="word"></div>
<br>
<input type="text" id="written">
</label>
<button id="btn">START</button>
</body>
Actually, there are some issues with your current solution.
First of all, you are changing the word.innerHTML for the first time after the 5 second interval, so it will instantly get replaced by GAME OVER, so with a difference of some millisecond the innerHTML will be change and you won't be able to see the desired output.
Then you are using input.innerHTML for your condition where innerHTML only uses for HTML elements which are containing some content within them (got opening and closing tags) whilst for taking input value you should use input.value.
Thus, in order to make your code work, you should replace the innerHTML in the very first place before executing the setInterval. Then after calling the interval if the condition met you should increment the i value and then call your interval again recursively.
So your final code should be something like this:
var btn = document.querySelector('#btn');
btn.addEventListener("click", myMove);
function myMove() {
var word = document.querySelector('#word');
var input = document.querySelector('#written');
var words = ['xylophone', 'cat', 'bat', 'chollima'];
var i = 0;
word.innerHTML = words[i];
var id = setInterval(frame, 5000);
function frame() {
if (input.value == word.innerHTML) {
clearInterval(id);
i = (i < 3) ? (i + 1) : 0;
word.innerHTML = words[i];
id = setInterval(frame, 5000)
} else {
word.innerHTML = 'GAME OVER';
}
}
}
<div id="heading">TYPING GAME</div>
<label>
<div id="word"></div>
<br>
<input type="text" id="written">
</label>
<button id="btn">START</button>
Don't use input.innerHTML, use input.value instead:
var btn= document.querySelector('#btn');
btn.addEventListener("click", myMove);
function myMove() {
var word = document.querySelector('#word');
var input=document.querySelector('#written');
var words=['xylophone', 'cat', 'bat', 'chollima'];
var i=0;
var id = setInterval(frame, 5000);
function frame() {
word.innerHTML=words[i];
i = (i < 3) ?( i+1) : 0;
if (input.value == word.innerHTML) {
clearInterval(id);
} else {
word.innerHTML='GAME OVER';
}
}
}
<div id="heading">TYPING GAME</div>
<label>
<div id="word"></div>
<br>
<input type="text" id="written">
</label>
<button id="btn">START</button>
</body>

if condition not running even when the condition satisfies

only the else statement in main.js statement where it reads scores-=1 runs and the if condition doesnt even when the condition satisfies. even after clicking on the right option my scores value doesnt increase by 1 instead it always decreasesby 1 which means it only satisfies the else statement
index.html
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
main.js
var questions =[{
question:'abcbcb',
options:['a','b','c','d'],
answer:'b'
}, {
question:"capital of india",
options:['delhi','mum','pune','kol'],
answer:'delhi'
}]
var x = Math.floor(Math.random() * (questions.length));
var scores = 0;
function gameplay(){
var quesn = document.getElementById('question');
quesn.innerHTML =questions[x].question;
for(i=0;i<4;i++){
var opt = document.getElementById('option'+i);
opt.innerHTML = questions[x].options[i];
var score = document.getElementById('scores');
score.innerHTML = scores;
}
}
gameplay();
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
For pure Javascript, use the innerHTML property.
For your example, use the following:
var spanVal = document.getElementById("option0").innerHTML;
var x = document.getElementById("option0").innerHTML;
console.log(x)
That is how you can attain the value, ".innerText" would also work.
(btw you labeled this as a question in java, this is javascript. Very different.
Hope this helps.
WORKING SAMPLE
Replace this
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
With this
function answer(ans)
{
var myAnswer = document.getElementById('option'+ans);
if(myAnswer.innerHTML == (questions[x].answer))
{
scores += 1;
}
else{
scores -= 1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
console.log(ans);
}
Then this
<p id="question"></p>
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>
With this
<p id="question"></p>
<div class="buttons">
<button id="button0" onclick ="answer('0')"><span id="option0"></span></button>
<button id="button1" onclick ="answer('1')"><span id="option1"></span></button>
<button id="button2" onclick ="answer('2')"><span id="option2"></span></button>
<button id="button3" onclick ="answer('3')"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>

Using InnerHTML on 144 different cells

I am creating a tile based game using tables. In each td cell,
<td>
<div id="image" style="display:none; display: fixed; right: 5; top:2;"><img src="http://thumb7.shutterstock.com/display_pic_with_logo/339217/339217,1272881114,1/stock-vector-hand-drawing-of-typical-house-along-the-canal-near-bangkok-in-thailand-52242874.jpgAttap"/></div>
<input id ="attap" type="submit" value="Show Div" onclick="showDiv(); if(submitted)this.disabled = true" />
<div id="welcomeDiv" style="display:none;"> <input type="submit" name="answer" value="Show Div" onclick="showDiv3(); if(submitted)this.disabled = true" /></div>
<div id="welcomeDiv3" style="display:none;"> <input type="submit" name="answer" value="Show Div" onclick="showDiv4(); if(submitted)this.disabled = true"" /></div>
<div id= "welcomeDiv4" style="display:none;"><input type="submit" name="answer" value="Show Div" onclick="showDiv5(); if(submitted)this.disabled = true"" /> </div>
</td>
Javascipt:
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
document.getElementById('image').style.display = "block";
submitted = true;
populationred +=20;
document.getElementById('population').innerHTML = populationred;
}
function showDiv3() {
document.getElementById('welcomeDiv3').style.display = "block";
document.getElementById("image").innerHTML = "'<img src='http://www.sgshophouses.com/images/Shophouses1.jpg'>'"
submitted = true;
populationred +=50;
document.getElementById('population').innerHTML = populationred;
}
function showDiv4() {
document.getElementById('welcomeDiv4').style.display = "block";
document.getElementById('image').innerHTML = "'<img src='http://singaporepropertylaunch.com.sg/wp-content/uploads/2015/04/HDB-resale-prices-fall-1.0.gif'>'"
submitted = true;
populationred +=100;
document.getElementById('population').innerHTML = populationred;
}
function showDiv5() {
document.getElementById('image').innerHTML = "'<img src='www.realestatechannel.com/assets_c/2010/06/Austonian-Condo-Tower-thumb- 120x238.jpg'>'"
submitted = true;
populationred +=200;
document.getElementById('population').innerHTML = populationred;
}
I need to repeat this for 144 cells. However, the problem is that when 1 button is clicked, the image will show up only at the first cell, hence the tedious way of solving this issue is to rename all the divs differently for every cell. Is there any more efficient ways?
You can refer here: www2.hci.edu.sg/t0104448b/cells.html for a "fiddle".
Shilly's comment had the right idea. I'm not entirely sure what your goal is but this is what I did, that looks reasonably what you're after. It should get you started.
There's only one click handler, on the <table> itself. It's effectively delegating the click. This saves memory because you're not creating a copy/closure for every cell. It costs some performance due to the delegating nature but for click handlers, it's generally okay. For mouseover handlers, that's another subject.
Using a <template> tag effectively gives you a DocumentFragment to work with and markup as HTML, instead of doing it in JavaScript (which can be tedious).
We clone that document fragment 144 times, injecting the proper description ('ShopHouse', 'HDB Flat', 'Condo', etc.) into each stamp of the template. Each clone is appended to a document fragment. Once our document fragment is done being modified, we inject it into the DOM via board.appendChild(frag);.
var board = document.getElementById('board');
var cellTmpl = document.getElementById('template-cell');
var cellTmplContent = cellTmpl.content;
var frag = document.createDocumentFragment(); // for performance
var submitted = false; // not sure what you intend to use this for
var descriptions = [ 'ShopHouse', 'HDB Flat', 'Condo' ]; // ... etc.
var cells = [];
for (var r = 0; r < 12; r++) {
var row = [];
cells.push(row);
var tr = document.createElement('tr');
frag.appendChild(tr);
for (var c = 0; c < 12; c++) {
var clone = document.importNode(cellTmplContent, true);
var index = r * 12 + c;
var description = index < descriptions.length ? descriptions[index] : 'Unknown place';
clone.querySelector('p.description').innerText = description;
tr.appendChild(clone);
row.push(clone);
}
}
board.appendChild(frag);
board.addEventListener('click', function(e) {
var button = e.target;
var td = button.parentElement;
var img = td.querySelector('img');
var p = td.querySelector('p.description');
button.disabled = true;
img.style.display = 'block';
p.style.display = 'block';
submitted = true;
});
// could do something with `cells` variable if you like. It's a two dimensional array of <td> elements
td {
background: #ccc;
border: 1px solid #000;
}
td > img {
display: none;
zoom: 0.2;
}
p.description {
display: none;
}
<table id="board">
</table>
<template id="template-cell">
<td>
<img src="http://thumb7.shutterstock.com/display_pic_with_logo/339217/339217,1272881114,1/stock-vector-hand-drawing-of-typical-house-along-the-canal-near-bangkok-in-thailand-52242874.jpgAttap"/>
<button>Show</button>
<p class="description"></p>
</td>
</template>

Javascript: Taking values from a textbox and adding it to the divs

So I have been racking my brain on how to add the a different value from the text box to a different div. So div1 gets the first thing the user typed, div2 gets the second, div3 gets the third, and so on. Everytime a user presses the "Add" button whatever the user typed will be added to one of the Div's above it. Right now I have it to where by pressing "Add" the value of the textbox is put in the first div. How do I create a function that will allow the user to add values to other divs. I assume you need a for loop but I do not know how to tackle it.
Here is my code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<div id="colorme" style = "cursor:pointer" onClick= "highlightLink()"><p id = "doubleStuff" ondblclick = "dubleStuff()">check this out</p></div>
<div id="colorme2" style = "cursor:pointer" onClick= "highlightLink2()"><p id = "doubleStuff2" ondblclick = "dubleStuff2()">check this out</p></div>
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick = "workInfoAdd()">Add</button>
<script>
function highlightLink(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'red';
highL2.style.backgroundColor = 'transparent';
};
function highlightLink2(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'transparent';
highL2.style.backgroundColor = 'red';
};
function dubleStuff(){
var x = "You double clicked it";
document.getElementById('putstuff').innerHTML = x;
};
function dubleStuff2(){
var x = "different stuff";
document.getElementById('putstuff').innerHTML = x;
};
function workInfoAdd(){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {
z.value = "";
}
};
</script>
</body>
</html>
Would something like this work.
var i = document.getElementById('addingInfo');
for(i = 0; i < 4; i++){
document.getElementbyId('workInfo').value = i //or some other variable that specifies the "adding info"
Any assistance would be greatly appreciated. As stated above after everytime the user presses ADD, the value they put into the text box will be added to the subsequent div. First add goes to first div, second goes to second div and so on.
You should probably write something like this:
var divIndex = 0;
function workInfoAdd() {
var z = document.getElementById('workInfo');
var p = document.getElementById('addingInfo' + (divIndex || ''));
if (!p) {
return;
}
if (z.value === null || z.value === "") {
alert('please enter work info');
} else {
p.innerHTML = z.value;
z.value = "";
}
divIndex++;
};
<div id="workInfo1" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo"></p>
</div>
<div id="workInfo12" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo1"></p>
</div>
<div id="workInfo13" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo2"></p>
</div>
<div id="workInfo14" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo3"></p>
</div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type="button" name="addWorkInfo" id="addWorkInfo" onclick="workInfoAdd()">Add</button>
Additionally you can use document.querySelector() for more advanced matching of elements ex.
var p = document.querySelector('.workInfo' + divIndex + ' > p.addingInfo' + divIndex);
Try the below code but remember that this solution should be used if you are going to limit the number of div (i.e only 3 or 4 divs) because if you want unlimited divs you will have to program an if-else statement for each possible div:
// Declare variable
var x = 0;
function workInfoAdd(){
// Increment
x++
// Check increment value
if(x == 1){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else { z.value = "";}
}
// Check increment value
else if(x == 2){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo1').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
// Check increment value
else if(x == 3){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo2').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
}
https://jsfiddle.net/6byvuzxf/
I have created check points as mentioned in my comment before.
Hope this helps.
See if this is what you want. I have added a class for all the p tags which will contain the information after click.
Html
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick ="workInfoAdd()">Add</button>
javascript
function workInfoAdd()
{
var elements = document.getElementsByClassName('addingInfo');
for(i=0;i<elements.length;i++)
{
if(elements[i].innerHTML == "")
{
elements[i].innerHTML = document.getElementById('workInfo').value;
document.getElementById('workInfo').value = "";
return;
}
}
}
http://jsfiddle.net/okLme061/1/

Have html show up after javascript function completes

I'm attempting to create a generic game of blackjack through javascript. The game starts when you click the start button:
<button type="button" onClick="deal()">Start Game</button>
which in turn runs the method deal:
function deal() {
card1 = Math.floor(Math.random() * 52);
card2 = Math.floor(Math.random() * 52);
card1 = changeCard(card1);
card2 = changeCard(card2);
score = card1 + card2;
for (var i = 0; i < aceAmount || score > 21;aceAmount--) {
score -= 10;
}
document.write("You were dealt a " + card1 + " and a " + card2 + " for a total of " + score + ".\nDo you wish to hit or pass?");
aceAmount = 0;
};
My question is once the deal method runs, how can I get two html buttons to show up on the screen, such as:
<button type="button" onClick="hit()">Hit</button>
<button type="button" onClick="pass()">Pass</button>
What to do?
Use the CSS display property to hide your buttons, then using the getElementById, method you "select" those buttons to do some "Javascripty" stuff on them.
Your HTML
<button id="hit_btn" style="display:none;" type="button" onClick="hit()">Hit</button>
<button id="pass_btn" style="display:none;" type="button" onClick="pass()">Pass</button>
and add this to your Javascript function:
document.getElementById('hit_btn').style.display = '';
document.getElementById('pass_btn').style.display = '';
and when you want to hide them back again
document.getElementById('hit_btn').style.display = 'none';
document.getElementById('pass_btn').style.display = 'none';
you could set an id or class on the buttons, and set a css rule with display:none. At the end of the deal function, set a line which changes display to block or inline. in jQuery, it would be
$('button.hit').css({visibility: "visible"})

Categories

Resources