Buttons controlling functions in javascripts - javascript

I have been making simple Javascript programs that I will run with different websites for my friends, and I have been trying to make a domination style (call of duty gamemode) program using buttons. I have looked at a website and have tried using the set intervals for it but I can't figure out how to make the buttons access the script.
Here is my code:
<!DOCTYPE html>
<html>
<body>
<p id = "blue"></p>
<p id = "red"></p>
<button onclick="StartA()">Start for Red</button>
<button onclick="StopA()">Stop for red</button>
<button onclick="StartB()">Start for Blue</button>
<button onclick="StopB()">Stop for Blue</button>
<script>
var startRed;
var startBlue;
var r=1;
var b=1;
var startA = function(){
var startRed = setInterval(function(){redscore++};,3000)
};
var startB = function(){
var startBlue = setInterval(function(){bluescore++};,3000)
};
var StopA = function(){
clearInterval(startRed);
};
var StopB = function() {
clearInterval(startBlue);
};
document.getElementById("blue").innerHTML=bluescore;
document.getElementById("red").innerHTML=redscore;
</script>
</body>
</html>

JavaScript is case sensitive. You are not consistent with case. Traditionally, JavaScript functions and variables start with a lower case letter and are camel cased.
You were reinitializing variables in functions that were already initialized in the global scope.
You weren't updating the ui with each score change, just at the start.
Below is updated code that should run as you intend. It might be worth while to turn your score keepers into a class, since they are redundant.
Updated Html
<p id="blue"></p>
<p id="red"></p>
<button onclick="startA()">Start for Red</button>
<button onclick="stopA()">Stop for red</button>
<button onclick="startB()">Start for Blue</button>
<button onclick="stopB()">Stop for Blue</button>
Updated javaScript
var startRed;
var startBlue;
var bluescore = 1;
var redscore = 1;
function startA() {
stopA();
startRed = setInterval(function () {
redscore++;
updateUI();
}, 3000)
};
function startB() {
stopB();
startBlue = setInterval(function () {
bluescore++;
updateUI();
}, 3000)
};
function stopA() {
clearInterval(startRed);
};
function stopB() {
clearInterval(startBlue);
};
function updateUI() {
document.getElementById("blue").innerHTML = bluescore;
document.getElementById("red").innerHTML = redscore;
}
updateUI();
jsFiddle

The following code is what you're looking for. The changes are:
Function names now match (startA() => StartA(), startB() => StartB(), etc.)
The <p> elements are updated within the interval (otherwise, they never update)
Remove local vars from within functions
You can view a jsfiddle here: http://jsfiddle.net/5tcNb/
<body>
<script>
var startRed, startBlue;
var redscore = 0, bluescore = 0;
var r = 1, b = 1;
function StartA() {
startRed = setInterval(function() {
redscore++;
document.getElementById("red").innerHTML = redscore;
}, 3000);
};
function StartB() {
startBlue = setInterval(function() {
bluescore++;
document.getElementById("blue").innerHTML = bluescore;
}, 3000);
};
function StopA() {
clearInterval(startRed);
};
function StopB() {
clearInterval(startBlue);
};
</script>
<p id="blue">0</p>
<p id="red">0</p>
<button onclick="StartA()">Start for Red</button>
<button onclick="StopA()">Stop for red</button>
<button onclick="StartB()">Start for Blue</button>
<button onclick="StopB()">Stop for Blue</button>
</body>

Related

Div innerHTML is not updated

I have the following test code and I want to update the div text and show one, two, three... but the result is only the last
Edit: Because any answer here it depends on "sleep", I don't actually use "sleep" on my code. I replaced the code with a for loop.
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
function dosomething() {
for(i=1; i<=500; i++) console.log(i);
}
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
document.getElementById("demo").innerHTML = 'one';
dosomething();
document.getElementById("demo").innerHTML = 'two';
dosomething();
document.getElementById("demo").innerHTML = 'three';
dosomething();
document.getElementById("demo").innerHTML = 'stop';
$myBtn.style.display = 'block';
}
</script>
</body>
</html>
In your example the system never has a chance to show you the one, two, three because it's tied up looping in your while and the page is not getting repainted.
You need to give it a break!
You can use the JS function setInterval for this - it will run a given function every time interval. But you also need to know when to stop it - and it's not absolutely accurate as there may be other things going on on your system so don't use it for e.g. implementing a stopwatch.
You can also use the JS function setTimeout which runs just the once, and then you run it again etc until you've output all the texts. Here's a small example:
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
let text = ['one', 'two', 'three', 'stop'];
let i = 0; //this indicates which text we are on
function test() {
document.getElementById("demo").innerHTML = text[i];
i++;
if ( i< text.length) {
setTimeout(test,1000);
}
}
</script>
</body>
</html>
You might be better off using the in-built setTimeout function, with some tweaks. Something like:
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
var contentArray = ['one', 'two', 'three', 'stop']; // <- declare the array of values you want here
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
for(let i = 0; i < contentArray.length; i++){ // <- using 'let' instead of 'var', so a new variable is created on each iteration
setTimeout(function() {
// console.log(i); // <- if you want to see the values, uncomment this line
document.getElementById("demo").innerHTML = contentArray[i];
}, 1000 * (i+1));
};
$myBtn.style.display = 'block';
}
</script>
</body>
</html>
With your self written sleep function, you stopped the Browser from passing the rendering Process until all your code had run.
You have to do something like this:
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
function sleep(sleepDurationMS) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, sleepDurationMS);
});
}
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
document.getElementById("demo").innerHTML = 'one';
sleep(1000).then(() => {
document.getElementById("demo").innerHTML = 'two';
sleep(1000).then(() => {
document.getElementById("demo").innerHTML = 'three';
sleep(1000).then(() => {
document.getElementById("demo").innerHTML = 'stop';
$myBtn.style.display = 'block';
});
});
});
}
</script>
</body>
JavaScript is Asynchronous so you will Get 'stop' as output .
Here I am using setTimeout Function() .
You don't need sleep function and here.
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
function test() {
let $myBtn = document.getElementById('myBtn');
$myBtn.style.display = 'none';
setTimeout(function () {document.getElementById("demo").innerHTML = 'one';},1000);
setTimeout(function () {document.getElementById("demo").innerHTML = 'two';},2000);
setTimeout(function () {document.getElementById("demo").innerHTML = 'three';},3000);
setTimeout(function () {document.getElementById("demo").innerHTML = 'stop';},4000);
$myBtn.style.display = 'block';
}
</script>
</body>
</html>
Your sleep function is blocking the Event Loop and this line
$myBtn.style.display = 'none';
causes the text to be hidden.
If you want that sleep feature, you should write it in async manner using Promise with setTimeout like this
<!DOCTYPE html>
<html>
<body>
<button onclick="test()" id="myBtn">test</button><br />
<div id="demo"></div>
<script>
const sleep = async (sleepDurationMS) => new Promise((resolve) => setTimeout(() =>
resolve(), sleepDurationMS))
async function test() {
let $myBtn = document.getElementById('myBtn');
document.getElementById("demo").innerHTML = 'one';
await sleep(1000);
document.getElementById("demo").innerHTML = 'two';
await sleep(1000);
document.getElementById("demo").innerHTML = 'three';
await sleep(1000);
document.getElementById("demo").innerHTML = 'stop';
}
</script>
</body>
</html>

Create variable by html button and use it in outside function

Is there any way to make it work?
I´ve read that "let can be only available inside the scope it's declared, like in for loop, on the other hand "var" can be accessed outside the loop for example"
HTML:
let create = document.getElementById("create");
let add = document.getElementById("add");
let cart = document.getElementById("cart");
create.onclick = function(){
var foo = "foo";
console.log(foo);
}
add.onclick = function(){
cart.innerHTML += foo;
}
<!DOCTYPE html>
<html>
<body>
<button id="create">create</button>
<button id="add">Add to cart</button>
<h2 id="cart">Cart: </h2>
</body>
<script type="text/javascript" src="test.js"></script>
</html>
You can attach the click event for add inside the show click event handler function by passing the the variable:
let show = document.getElementById("show");
let add = document.getElementById("add");
let cart = document.getElementById("cart");
show.onclick = function(){
var foo = "foo";
console.log(foo);
add.addEventListener('click', function() { addToCart(foo); });
}
function addToCart(f){
cart.innerHTML += f;
}
<button id="show">Show</button>
<button id="add">Add to cart</button>
<h2 id="cart">Cart: </h2>

Javascript showing wrong results

HTML code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="score-board.css">
<title>Score Board App</title>
</head>
<body>
<div id="playersscores">
<span id="p1score">0</span><span> To </span> <span id="p2score">0</span>
</div>
<p>Playing to <span id="score">5</span></p>
<input type="field" value="5" ></input>
<button id="p1clicked">Player one</button>
<button id="p2clicked">Player two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score-board.js"></script>
</body>
</html>
Javascript is :
Whenever this code is loaded :
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score (player_result) {
//var score = parseInt(player_result.innerText) + 1;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener("onclick", increment_score(p1result))
Whenever this code is loaded in a browser, the span showing the result for player 1 is showing one directly without clicking on player 1 button. i'm not sure what is wrong with the event listener im using.
The event is click instead of onclick
The event listener should be a reference to the function itself, not the result of a function call (which increments the score by 1)
Inside the function, you can access the button with this:
The code could look like this:
function increment_score() {
var player_result = this;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener('click', increment_score);
Use click event not onclick
You pass result of function not instead reference to function
If you need pass parameters to event handler - you can use bind:
p1clicked.addEventListener("click", increment_score.bind({result: p1result, inc: 1 }) )
p2clicked.addEventListener("click", increment_score.bind({result: p2result, inc: 2 }) )
function increment_score () {
var score = parseInt(this.result.innerText) + this.inc;
this.result.innerText = score;
}
[ https://jsfiddle.net/6vw8ay3x/ ]
You have a couple problems there. First, when calling the addEventListener function, you need to specify just "click", not "onclick". Secondly, when you pass the function to addEventListener, you just want it to be a reference to the function not an actual function call. The following changes will net you the result you are seeking.
function increment_score () {
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
}
p1clicked.addEventListener("click", increment_score);
But since you want to be able to use the same function for multiple players, then I would suggest adding the "onclick" handler to the HTML which will allow you to pass the element you want to increment. Then your HTML code would look like this:
<button id="p1clicked" onclick="increment_score_with_param(p1result);">Player one</button>
<button id="p2clicked" onclick="increment_score_with_param(p2result);">Player two</button>
and your javascript would be:
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score_with_param (player_result) {
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
window.onload = function(){
var p1result = document.querySelector('#p1score');
var p2result = document.querySelector('#p2score');
var p1clicked = document.querySelector('#p1clicked');
p1clicked.addEventListener("click", function(e){
e.preventDefault();
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
});
}

Trying to set a move in tic tac toe game, but I keep getting undefined when I call back the function

I'm not sure what I'm doing wrong. I'm calling my function with addEventListener down at the bottom, but for some reason my setMove function is giving me undefined. I'm trying to put a 'X' or an 'O' on one of the buttons when clicked, and the way I'm doing that is setting my variable buttonClicked which will give me the DOM object, then I iterate through the object and that's where I get stuck. I'm not sure what to do after that. I'm a beginner in JavaScript, so please take it easy on me. Thank you in advance!!! :)
HTML:
<html>
<head>
<title>Tic Tac Toe</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id="wrap">
<div id="board">
<h2>Tic Tac Toe</h2>
<div>
<button class="btn"></button>
<button class="btn"></button>
<button class="btn"></button>
</div>
<div>
<button class="btn"></button>
<button class="btn"></button>
<button class="btn"></button>
</div>
<div>
<button class="btn"></button>
<button class="btn"></button>
<button class="btn"></button>
</div>
</div>
<div id="gameOutput"></div>
</div>
</body>
</html>
JavaScript:
var players = ['X', 'O'];
var currentMove = 0;
var gameOver = false;
var output = document.querySelector('#gameOutput');
var buttonClicked = document.querySelectorAll('#board .btn');
output.innerText = "Game is ready. " + players[currentMove] + " Turn.";
// sets X or O
var setMove = function (move, mark) {
for (var i = 0; i < move.length; i++) {
move[i].innertText = mark;
}
};
//some code
var buttonClickHandler = function() {
//some more code
if (valid(buttonClicked) === true) {
this.style.backgroundColor = '#0D771A';
console.log(setMove(buttonClicked, players[currentMove]));
} else if (valid(button) === false) {
output.innerText = "That is not a valid move :(";
};
//some more code
});
for (var i = 0;i < buttonClicked.length; i++) {
buttonClicked[i].addEventListener('click', buttonClickHandler);
}
You have an extra bracket after defining the buttonClickHandler function.
Besides, you are using a function valid that is not defined.. Please add it to the question if it's there or define it yourself and try again.
var buttonClickHandler = function() {
//some more code
if (valid(buttonClicked) === true) {
this.style.backgroundColor = '#0D771A';
console.log(setMove(buttonClicked, players[currentMove]));
} else if (valid(button) === false) {
output.innerText = "That is not a valid move :(";
} // <<<<<<<<<<<<<<<<<< removing semi-colon
//some more code
}; // <<<<<<<<<<<<<<< removing extra bracket

How to modify a function in a page using Bookmarklet?

Lets say I have an HTML page which has its own function myFunction()
<!DOCTYPE html>
<html>
<body>
<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
alert("stack overflow");
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
I want to change the myFunction()definition like this
function myFunction() {
//alert("stack overflow");
document.getElementById("demo").innerHTML = "Hello World";
}
using bookmarklet.So is there any way to change the def temporarily ?
I tried using the Chrome Console to change its def and also remain successful,but I want to change it using bookmarklets.So please help me.
As it's a global, you can do this in your bookmarklet:
var oldFunction = myFunction;
myFunction = function() {
alert("Hello world!");
};
Or if you enclose your bookmarklet in a scping function (usually a good idea), probably store the old value on a window property instead of a local var (so you can access it from another bookmarklet to restore it later):
window.oldFunction = myFunction;
myFunction = function() {
alert("Hello world!");
};
Another bookmarklet could set it back again:
myFunction = window.oldFunction; // or just = oldFunction if using a local var
Live Example:
function myFunction() {
alert("Original function");
}
document.getElementById("btn-override").addEventListener("click", function() {
window.oldFunction = myFunction;
myFunction = function() {
alert("New function");
};
}, false);
document.getElementById("btn-restore").addEventListener("click", function() {
myFunction = window.oldFunction;
}, false);
<input type="button" id="btn-call" value="Click to call myFunction" onclick="myFunction()">
<input type="button" id="btn-override" value="Click to override it">
<input type="button" id="btn-restore" value="Click to restore it">
Try this :
javascript: myFunction = function(){console.log('c')}

Categories