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)
}
Related
I am trying to decrement the variable Stock by 1 each time I click the button but it's not working. The value on the website stays the same no matter how many times I click the button:
var Stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = Stock;
}
function ButtonFunction() {
Stock--;
}
<body onload="myFunction">
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
Your function only changes the value of the Stock variable.
It doesn't change the value of document.getElementById("myText").innerHTML which only gets changed when you call myFunction (something you never do).
You need to:
Actually call myFunction when the document loads
Call it again whenever you change the variable.
let stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = stock;
}
function buttonFunction() {
stock--;
myFunction();
}
document.querySelector("button").addEventListener("click", buttonFunction);
addEventListener("load", myFunction);
<button>ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
Also note that by convention, variable names which start with a capital letter are reserved for classes and constructor functions in JS, so rename your variables.
It looks like the variable is being decremented, but the inner text of the span is not then updated.
Try calling myfunction() after each click ;)
There's a number of things going on here. The one I think you're primarily interested in has been answered by Quentin. Others however remain and are (I think) far better habits to get into than variable naming conventions.
Inline event handlers = bad. Events that can be removed or supplemented = good. Use attachEventListener for the most control.
Functions with names that offer nothing are a pain. Names are the most helpful when they're descriptive.
Functions that change and display a variable can be traps. It's often better to have a third function which calls both a function to change something and another function to display it.
Here's yet another approach:
window.addEventListener('load', onLoaded, false);
function onLoaded(evt) {
displayStock();
document.querySelector('button').addEventListener('click', onButtonPressed, false);
}
var unitsOfStock = 10;
function displayStock() {
document.getElementById('myText').textContent = unitsOfStock;
if (unitsOfStock == 1)
document.getElementById('plural').textContent = '';
else
document.getElementById('plural').textContent = 's';
}
function decreaseStock() {
unitsOfStock--;
}
function onButtonPressed() {
decreaseStock();
displayStock();
}
<button>ClickMe</button>
<h1>The value for Stock is: <span id="myText"></span> unit<span id='plural'></span></h1>
var Stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = Stock;
}
function ButtonFunction() {
Stock--;
myFunction();
}
<body onload="myFunction()">
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
I hope it helps you. You have to call myFunction to show the new value of Stock variable in myText id in your click handler ButtonFunction().
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = Stock;
}
function ButtonFunction() {
Stock--;
myFunction();
}
</script>
</head>
<body onload="myFunction" >
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
</html>
Whenever you click the 'Click me' button, ButtonFunction() will be called. and document.getElementById("myText") get find the html element with the id myText and reference itself to the html element. innerHTML will allow you to place your html code inside it and innerText allows you to put your text the html element with an id of myText.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Stock = 10;
function ButtonFunction() {
Stock--;
document.getElementById("myText").innerHTML = Stock;
}
</script>
</head>
<body>
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
</html>
I need to play some text and ONLY THEN perform the following actions (e.g. hiding the "pause" and "stop" buttons), but they are hidden IMMEDIATELY when I start playing the text. Simplified situation - see code.
Many thanks for the advice..
<!DOCTYPE html>
<html>
<body>
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<script>
function Voice(id){
var element = document.getElementById(id);
var text = element.innerText;
responsiveVoice.speak(text, "UK English Male", {onend: Hide("div1")});
}
function Hide(id){
var element = document.getElementById(id);
element.style="visibility: hidden";
}
</script>
<div id="div1">This is the first line.</div>
<div id="div2" onclick = 'Voice("div2")'>
This is the second line.
</div>
<br>
Click on the second line to play its text. The first line should be hidden after the message is played.<br>
But it is hidden IMMEDIATELY after clicking. What is wrong?
</body>
</html>
The solution is to use arrow: {onend: () => Hide()} instead of {onend: Hide()} (Thanks to CertainPerformance).
onstart:, onend: and rate: can even be used simultaneously. There is only one small problem - after changing the content of the page, there is a long delay when using the ResponsiveVoice function for the first time. See code:
<!DOCTYPE html>
<html>
<body>
<script src='https://code.responsivevoice.org/responsivevoice.js'>
</script>
<script>
function Read(id){
var element = document.getElementById(id);
var text = element.innerText;
responsiveVoice.speak(text, "UK English Male", {rate: 1.3, onstart: () => Show(), onend: () => Hide()});
}
function Show(){
var element = document.getElementById("Pause");
element.style="visibility: visible";
}
function Hide(){
var element = document.getElementById("Pause");
element.style="visibility: hidden";
}
</script>
<div id="div" onclick = 'Read("div")'>This is text to read.</div>
<br>
<input type = "button"
id = "Pause"
value = "Pause"
style = "visibility: hidden" />
</body>
</html>
You need to pass a function that calls Hide, rather than calling Hide immediately:
{onend: Hide("div1")}
calls hide as soon as that line is evaluated. It needs to be:
{onend: () => Hide("div1")}
<!DOCTYPE html>
<html>
<body>
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<script>
function Voice(id){
var element = document.getElementById(id);
var text = element.innerText;
responsiveVoice.speak(text, "UK English Male", {onend: () => Hide("div1")});
}
function Hide(id){
var element = document.getElementById(id);
element.style="visibility: hidden";
}
</script>
<div id="div1">This is the first line.</div>
<div id="div2" onclick = 'Voice("div2")'>
This is the second line.
</div>
<br>
Click on the second line to play its text. The first line should be hidden after the message is played.<br>
But it is hidden IMMEDIATELY after clicking. What is wrong?
</body>
</html>
I have a button. When I click the button, I want an image of a cat to be created. I have created a function to do this. I have added an event listener to the button that triggers the function when the button is clicked. But no such image is created. Here's the code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="1">hello</button>
<script>
function create(){
var image= document.createElement("img")
image.src="https://encrypted-tbn0.gstatic.com/images?
q=tbn%3AANd9GcQeP6zBFWjK10gNYUK1kxM6I-AbF8vK_zPGSHrk38JzCb_5ZpRd&usqp=CAU"
document.body.appendChild(image)
}
var element=document.getElementById("1")
element.addEventListener("click", create)
</script>
</body>
</html>
That because the url got corrupted and white space got introduced between images? and next line. Concat them using + or copy the url , try in the browser and then copy the same url from browser and put it between quotes
function create() {
var image = document.createElement("img")
image.src="https://encrypted-tbn0.gstatic.com/images?"+
"q=tbn%3AANd9GcQeP6zBFWjK10gNYUK1kxM6I-AbF8vK_zPGSHrk38JzCb_5ZpRd&usqp=CAU";
document.body.appendChild(image)
}
var element = document.getElementById("1")
element.addEventListener("click", create)
<button id="1">hello</button>
Add semicolons and remove the linebreak in the url:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="1">hello</button>
<script>
function create(){
var image= document.createElement("img");
image.src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQeP6zBFWjK10gNYUK1kxM6I-AbF8vK_zPGSHrk38JzCb_5ZpRd&usqp=CAU";
document.body.appendChild(image);
}
var element=document.getElementById("1");
element.addEventListener("click", create);
</script>
</body>
</html>
i'm trying to create a DIV with 100x100 px and it shold be red, every time a button is clicked, i did this code but its not working:
<html>
<title>
create new div
</title>
<body>
<button id="createsquare">
Cria QUADRADO
</button>
<script>
function fcreatesquare()
{
var crsq = document.createElement('div', 'id=created', 'widght=100px', 'wheidght=100px','color=black');
return crsq;
}
var createsquare = document.getElementById('createsquare');
createsquare.onclick(fcreatesquare);
</script>
</body>
</html>
Check out the appendChild function: https://www.w3schools.com/jsref/met_node_appendchild.asp
function fcreatesquare() {
var crsq = document.createElement('div', 'id=created', 'widght=100px', 'wheidght=100px','color=black');
document.getElementsByTagName("body")[0].appendChild(crsq);
}
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)