{button}.onclick to change textContent - javascript

I'm trying make simple game "Rock Paper Scissors". At this moment I got stuck in changing value of Global Variable. Situation: (for ex.) Click => [Rock]. I have to store this into Global Variable's ("playerMove").
const rock = document.createElement('button');
/*
*/
let playerMove;
playerMove = '';
I arleady try
rock.onclick = function() {
playerMove = 'Rock'; // Test in function..
}
but Its only work in function (Yea, we all know global variable doesn't work that way so..). I may be able to fix that problem soon but at this moment my mind can't think any better than this :|, I want help to find any good resource about this to (how) change textContent / Value of element by clicking on button.
Sorry for my bad English..

You can use HTMLButtonElement.addEventListener() to listen for "click" events, and then do whatever you want to, a simple demo
const btn = document.getElementById('test');
const container = document.getElementById('val');
btn.addEventListener('click', () => {
container.textContent = 'works'
})
<div id="val">test</div>
<button id="test">click me</button>

To update the playerMove variable you could use a function that set that value.
document.createElement('button');
const rock = document.querySelector('button');
let playerMove = ''
const updateMove = (move) => {
playerMove = move;
}
rock.onclick = () => {
updateMove('Rock');
}

const rock = document.getElementById('button');
console.log(rock)
let playerMove;
playerMove = '';
rock.addEventListener('click',(e)=>{
playerMove =e.target.innerHTML;
console.log(playerMove);
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Aide</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<header>
<button id="button">Rock</button>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
strong text
This code works perfectly.
it takes the text that the button contains.
I think your mistake is that you didn't declare that the button you created a js is a child of body.

Ty guys
Well, I will explain lil more about what playerMove was doing..
playerText.textContent = playerMove;
so I simple was trying to change playerMove but after I see AnanthDev answer >>
function playerMove(element, move) {
element.addEventListener('click', () => {
playerText.textContent = move;
})
}
playerMove(rock, 'Rock');
playerMove(scissors, 'Scissors');
playerMove(paper, 'Paper');

Related

Setting button.onclick via button click activates on first button press

So I'm trying to create a button that when pressed changes the content of an html page and updates the button to change its next function. However, whenever I use .onclick I end up printing the "2" to the console while still on the first press of the button. I've tried using .click as well, and the only thing that I can find that works is setting the function directly, however this is untidy and long. I wondered if there was another way to do this with cleaner code.
html:
<!DOCTYPE html>
<html lang="en-US">
<body>
<script src="Path_To_File"></script>
<p id="text">
<!-- text here -->
</p>
<button id="b1" type="button" onclick="pageFlip(1)">Button</button>
</body>
</html>
JS:
function pageFlip(page) {
var p = document.getElementById("text");
var b1 = document.getElementById("b1");
var b2 = document.getElementById("b2");
switch (page) {
case 1:
p.innerHTML = "newText";
b1.innerHTML = "newText";
b1.onclick = pageFlip(2);
break;
case 2:
console.log("2");
break;
}
}
What works:
b1.onclick = function changeButton() {
pageFlip(2)
}

Move the dynamically created buttons in clockwise using JavaScript

I have some input type=button which are created dynamically using JavaScript. Here I need to shift those clockwise while click on button. Here is my code:
<!-- Enter your HTML code here -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Buttons Grid</title>
</head>
<body>
<div id="btns" style="width:75%;">
</div>
<script>
for(var i=0;i<9;i++){
var index=i+1;
var element = document.createElement("input");
element.type = "button";
element.value = index;
element.id = "btn"+index;
element.setAttribute("style","width:30%;height:48px;font-size:24px");
var foo = document.getElementById("btns");
//Append the element in page (in span).
foo.appendChild(element);
}
document.getElementById("btn5").onclick=function(){
}
</script>
</body>
</html>
Here I need when user will click one button 5 the buttons present around button5 will move clockwise means button4 will shift to first place without changing its ids.
Something like this?
let container = document.querySelector("#btns");
container.insertBefore(container.lastElementChild, container.firstElementChild);
// or this ?
// container.appendChild(container.firstElementChild);
I suppose you don't need to create the buttons in js. You can create in html code. And just play with innertext of btns. My approach was like this;
btn5.addEventListener('click', () => {
const textofBtn = btn1.innerText;
btn1.innerText = btn4.innerText;
btn4.innerText = btn7.innerText;
btn7.innerText = btn8.innerText;
btn8.innerText = btn9.innerText;
btn9.innerText = btn6.innerText;
btn6.innerText = btn3.innerText;
btn3.innerText = btn2.innerText;
btn2.innerText = textofBtn;
});
but I saw another solution looking like more elegant here is you can check;
let nums=[1,2,3,6,9,8,7,4];
const ids=[1,2,3,6,9,8,7,4];
let btn5=document.getElementById("btn5");
btn5.onclick=function() {
nums.unshift(nums.pop());
for (i=0; i<=7; i++) {
document.getElementById("btn"+ids[i]).innerHTML=nums[i];
}
}
// writed by mark_russellbro1(hackerrank username)

onclick function not working in JS

New here. I'm trying to use onclick to switch out some images that i have assigned to variables in my script but i can't get it to work. Any ideas?
let doorImage1 = document.getElementById("door1");
let botDoorPath ='https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/robot.svg';
doorImage1.onclick= () =>{
doorImage1.src = botDoorPath;
}
This did not work for me until I set the src in the element to something first. Seems to be working, so perhaps your element was not found. Look at console to see if it was undefined.
let doorImage1 = document.getElementById("door1");
let botDoorPath = 'https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/robot.svg';
doorImage1.onclick = () => {
console.log('click')
doorImage1.src = botDoorPath;
}
<html>
<img src='./missing.png' id='door1'></img>
</html>

How do I clear inner HTML

I've been fiddling with this for a while but it won't work and I can't figure out why. Please help. Here is what I have:
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
The mouseover works and displays the text in the div, but when I move the mouse out of the h1 tag, the text stays there and I don't know why, help would be appreciated.
The problem appears to be that the global symbol clear is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah), it works just fine:
Live: Version using clear which fails | Version using blah which works
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function blah() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.
A corollary to that is to not use old-style onxyz=... attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 id="the-header">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
// Scoping function makes the declarations within
// it *not* globals
(function(){
var header = document.getElementById("the-header");
header.onmouseover = function() {
go('The dog is in its shed');
};
header.onmouseout = clear;
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
})();
</script>
</body>
</html>
...and even better, use DOM2's addEventListener (or attachEvent on IE8 and earlier) so you can have multiple handlers for an event on an element.
const destroy = container => {
document.getElementById(container).innerHTML = '';
};
Faster previous
const destroyFast = container => {
const el = document.getElementById(container);
while (el.firstChild) el.removeChild(el.firstChild);
};
The h1 tags unfortunately do not receive the onmouseout events.
The simple Javascript snippet below will work for all elements and uses only 1 mouse event.
Note: "The borders in the snippet are applied to provide a visual demarcation of the elements."
document.body.onmousemove = function(){ move("The dog is in its shed"); };
document.body.style.border = "2px solid red";
document.getElementById("h1Tag").style.border = "2px solid blue";
function move(what) {
if(event.target.id == "h1Tag"){ document.getElementById("goy").innerHTML = "what"; } else { document.getElementById("goy").innerHTML = ""; }
}
<h1 id="h1Tag">lalala</h1>
<div id="goy"></div>
This can also be done in pure CSS by adding the hover selector css property to the h1 tag.
Take a look at this. a clean and simple solution using jQuery.
http://jsfiddle.net/ma2Yd/
<h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
$(function() {
$("h1").on('mouseover', function() {
$("#goy").text('The dog is in its shed');
}).on('mouseout', function() {
$("#goy").text("");
});
});

Javascript Sound Start/Stop and Image Change

I am new to JS and I have a pretty simple-seeming problem.
I want to have a small image that when clicked changes to a different image and at the same time begins playing a looped sound file. When the image is clicked a second time it changes back to the original image and also stops the sound file.
You can think of it as a button that says "start". when "start" is clicked it loops the sound and changes to "stop" and when "stop" is clicked it goes back to start and the sound ceases playing.
I've gotten as far as creating none-displayed checkbox inside of a label which is a square that when checked plays sound and when unchecked stops sound. Problem is I can't get the checkbox to change into different images with "check", "uncheck".
I've also got some code that has a link change images, but I cannot figure out how to make it play the sound.
SO basically i need to combine these two things. BUT I CAN'T figure out how. And I've been googling for the past two days nonstop but cannot find a clearcut and simple answer.
It may help to know that I plan on having many of these small clickable images on the same page, so the Javascript needs to be able to be light but effect all of the links or divs or whatever they are in the end.
Sorry for such a long question. Anybody?
Thanks in advance!
<html>
<head>
<script type="text/javascript">
var pos = 0
var sId = 'sound';
function change() {
if(pos == 0) {
pos = 1;
document.getElementById('btn').src="http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png";
var e = document.createElement('embed');
e.setAttribute('src','beep.mp3');
e.setAttribute('id',sId);
e.setAttribute('hidden','true');
e.setAttribute('autostart','true');
e.setAttribute('loop','true');
document.body.appendChild(e);
} else {
pos = 0;
document.getElementById('btn').src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png";
document.body.removeChild(document.getElementById(sId));
}
}
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="change()" id="btn" />
</body>
</html>
How about that, I think it should work.
Edit:
Here is an OO version that should do what you need:
<html>
<head>
<script type="text/javascript">
function imageSwitch(_imgID,_imgStart,_imgStop,_soundFile) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.soundFile = _soundFile;
this.pos = 0;
this.e;
this.change = function() {
if(this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.e = document.createElement('embed');
this.e.setAttribute('src',this.soundFile);
this.e.setAttribute('id','sound'+this.imgID);
this.e.setAttribute('hidden','true');
this.e.setAttribute('autostart','true');
this.e.setAttribute('loop','true');
document.body.appendChild(this.e);
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.e.parentNode.removeChild(this.e);
}
}
}
</script>
<script type="text/javascript">
var abc = new imageSwitch('btn1','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
var def = new imageSwitch('btn2','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="abc.change()" id="btn1" />
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="def.change()" id="btn2" />
</body>
</html>

Categories

Resources