When does a change to TextContent get displayed? - javascript

I'm working on Rock/Paper/Scissors game for the Odin Project. I display the result of a game in a div resultMsg, and a running tally based on that result in countMsg. Both those items are divs in the HTML and they work correctly. After a total of 5 games are won or lost, I want to (in order) clear the textContent messages, use an "alert" to give a final tally, and start over.
I expected that the two lines highlighted with "->" would clear the textContent message. However they do not until after I click [OK] to clear the alert. I'd really like to understand why that is.
The HTML relevant body:
<div id="playersChoice">
<button id='rock'>Rock</button>
<button id='paper'>Paper</button>
<button id='scissors'>Scissors</button>
</div>
<div id="result">
</div>
<div id="count">
</div>
The Javascript that's relevant.
let gamesPlayed = 0;
let playerWon = 0;
let computerWon = 0;
const countMsg = document.querySelector ('#count');
const resultMsg = document.querySelector ('#result');
// Get all the buttons within playerschoice container
const userButton = document.querySelectorAll ('#playersChoice > button');
// For each button, create an event listener for the click which will play a round.
// Note the Button.ID identifies the players choice.
userButton.forEach(button => {
button.addEventListener('click', function() {
gamesPlayed++;
resultMsg.textContent = playRound(button.id, computerPlay());
// if there are less than 5 clear wins or losses
if ((playerWon + computerWon) < 5) {
countMsg.textContent = "The current tally is your " + playerWon + " wins to the computers " + computerWon + ".";
} else {
// there have been 5 definitive games, declare the overall winner!
-> resultMsg.textContent = '';
-> countMsg.textContent = '';
gamesPlayed = 0;
playerWon = 0;
computerWon = 0;
alert("Best of 5 series results : You won " + playerWon +", lost " + computerWon + ", and tied "+ (5-playerWon-computerWon) + " of them.");
}
});
});
'''

alert() will block the current script execution, but it seems to also blocks the DOM update. That's why even though the assignement to textContent is before the alert, the text is only shown after the alert has been clicked, and the execution has resumed.
You can use a very small setTimeout to allow the DOM to update before the alert() fires:
const div = document.querySelector("div");
function test1() {
div.textContent = "Test without timeout!";
alert("Test1!");
}
function test2() {
div.textContent = "Test with timeout!";
setTimeout(() => alert("Test2!"), 10);
}
<button onclick="test1()">Test</button>
<button onclick="test2()">Test with timeout</button>
<h4>Text content:</h4>
<div></div>
Edit:
I researched a bit more, and to be more precise, DOM updates happen only after the script has finished. Since alert() blocks the current script, the DOM update will only happen after the alert has been dismissed.
This behavior can also be seen with the following snippet:
function wait(ms) {
var start = Date.now(),
now = start;
while (now - start < ms) {
now = Date.now();
}
}
function test() {
document.querySelector("div").textContent = "Test with delay!";
wait(2000);
}
<button onclick="test()">Test with delay</button>
<div></div>

Related

Dynamically increasing font size

I would like to increase the font size of the paragraph as well as the font size of the number in the button.
I copied and pasted my sizer function from StackOverflow (a few alterations) and thought it would work and still can't get it to work. Can someone help?
Since I've spent so much time on just the first part, as a beginner programmer, I'm wondering what I am missing. Does anyone have any ideas from my code or their experience as to what I might be missing?
Thanks as always.
<html>
<button onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
sizer = function changeFontSize() {
div = document.getElementById("test");
currentFont = div.style.fontSize.replace("pt", "");
div.style.fontSize = parseInt(currentFont) + parseInt(clicks) + "pt";
}
</script>
</html>
Some things here:
I woudn't append two functions to your onclick here. Just append one and call your second function from the first one that gets fired via onclick. That looks a lot more tidy
Don't forget to put var before every variable, without it's not valid JavaScript
I didn't quite understand what you tried with your currentFont variable, so I removed it. It's not necessary and causes the script to not working correctly
<html>
<button onclick='incrementer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
var clicks = 0;
var incrementer = function() {
clicks += 1;
var click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
sizer();
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
div.style.fontSize = parseInt(clicks) + "pt";
}
</script>
</html>
Here's a from-scratch version that does what you're asking for. I'll point out a few things that I did to help you out.
https://codepen.io/anon/pen/VBPpZL?editors=1010
<html>
<body>
<button id="count">0</button>
<p id="test">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</body>
</html>
JS:
window.addEventListener('load', () => {
const button = document.querySelector('#count');
const paragraph = document.querySelector('#test');
const startingFontSize = window.getComputedStyle(document.body, null)
.getPropertyValue('font-size')
.slice(0, 2) * 1;
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
// this is a template literal
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const fontSize = `${startingFontSize + clicks}px`;
button.innerHTML = clicks;
button.style.fontSize = fontSize;
paragraph.style.fontSize = fontSize;
});
});
The code runs when the page is loaded, so we attach an event listener on the window object listening for the load event.
We then store references to the button and the paragraph elements. These are const variables because their values won't change. This also limits their scope to the containing function.
We get the initial font size for the body element, because in this example we aren't explicitly setting a base font in css so we're just using the one for the document. getComputedStyle is a somewhat expensive operation, and in this case we only need to get it in the beginning because it won't change, so we also store it as a const. The value is returned as a string like "16px" but we need the number, hence the slice and multiplying by one to cast the string into a number. parseInt would also do the same thing.
Notice that clicks is defined with let. This means that the variable can be changed. var still works of course, but in modern practices its best to use const and let when declaring variables. This is partly because it forces you to think about what kind of data you're working with.
We add an event listener to the button element and listen for the click event. First, we increment the clicks variable. Then we declare fontSize using a template literal which adds our new clicks count to the startingFontSize and "px" to get a string.
Finally, the innerHTML value of the button element is updated. Then we update the fontStyle property for both elements.
The issue here is that there is no initial value for the fontSize of your <p> tag so div.style.fontSize returns an empty string.
You can use window.getComputedStyle instead of div.style.fontSize and you will get the current fontSize.
There is already a post explaining this method
https://stackoverflow.com/a/15195345/7190518
You don't have an initial font-size style on your <p> tag, so it div.style.fontSize is always empty. Also, best practice is to always use var when introducing new variables in javascript.
One good trick to help debugging things like these is to use console.log() at various points, and see whats coming out in your browser console. I used console.log(div.style.fontSize) and the answer became clear.
Working below after adding <p style='font-size:12px'>a</p>:
<html>
<button style='font-size:12px;' onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test' style='font-size:12px;'>a</p>
<script>
var clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
var btn = document.getElementById("count");
var newSize = parseInt(div.style.fontSize.replace("pt", "")) + parseInt(clicks);
div.style.fontSize = newSize + "pt";
btn.style.fontSize = newSize + "pt";
}
</script>
</html>
I don't understand the logic of this solution, but you can simplify it avoiding to use a lot of var (anyway always prefer let or const if you don't need to change), using a single function and writing less code.
function increment(e){
const ctrl = document.getElementById('test');
let current = parseInt(e.dataset.size);
current += 1;
e.innerHTML = current;
e.dataset.size = current;
ctrl.style.fontSize = current + 'pt';
}
<button onclick="increment(this);" data-size="20">20</button>
<p id='test' style="font-size:20pt;">A</p>

NaN return value from function Javascript || Function Execution Order

Newbie in Javascript here, and after hours digging trough other questions I'm not quite sure how to explain this to be honest, but i'll give it my best, hopefully you'll be able to help me.
HTML:
<div id='header'> <h1> Pastel Land </h1> </div>
<div id='container'>
<div id='readyContainer'>
<h3> This game will start in </h3>
<h1 id='readySeconds'> </h1>
</div>
<div id='shape'> </div>
</div>
<div id='features'>
<button id='start'> START </button>
<button id='stop'> STOP </button>
<p id='timeBox'></p>
<p id='timeAverageBox'></p>
</div>
<div id='testbox'> </div>
FULL SCRIPT:
document.getElementById('start').onclick = function () {
document.getElementById('readyContainer').style.display = 'block';
document.getElementById('readySeconds').innerHTML = '3'
setTimeout(function() {document.getElementById('readySeconds').innerHTML = '2'}, 1000);
setTimeout(function() {document.getElementById('readySeconds').innerHTML = '1'}, 2000);
setTimeout(readyAlert,3000);
setTimeout(displayShape, 3000);
var style = document.getElementById('shape').style;
var el = document.getElementById('shape');
el.addEventListener("click", a, false);
el.addEventListener("click", b, false);
function a() {
style.display = "none";
displayShapeDelay(); // calls the delay function
}
function b() {
end = new Date().getTime(); // saves time when clicked
var time = (end - start)/1000 ; // calculates interval from shape creation until click
document.getElementById('timeBox').innerHTML = time + 's';
return time;
}
document.getElementById('testbox').innerHTML = b();
function readyAlert() {
document.getElementById('readyContainer').style.display = 'none';
}
function getRandomColor() {
var hex = ["#96ceb4", "#ffeead", "#ff6f69", "#ffcc5c", "#88db8b0", "#528491"];
var color = hex[Math.floor(Math.random() * 6)]; // generates integer numbers [0,5], selects indexed item from hex
return color;
}
function displayShape () {
var percentages = [];
for (var i=0; i<4; i++){ // generates a list with 4 different random integer values [5,60]
percentages.push((Math.floor(Math.random() * 61) + 5));
}
var width = (Math.floor(Math.random() * 61) + 5); // generates integer numbers [5,60]
var shapeRand = Math.random()
if (shapeRand < 0.3) { // circle
style.borderRadius = "50%";
} else if (shapeRand >= 0.3 && shapeRand < 0.6) { // random shape
style.borderTopLeftRadius = percentages[0] + "%";
style.borderBottomRightRadius = percentages[1] + "%";
style.borderTopRightRadius = percentages[2] + "%";
style.borderBottomLeftRadius = percentages[3] + "%";
} else { // square
style.borderRadius = "0%";
}
//general shape styles
style.width = width + "%";
style.height = width + "%";
style.display = "block";
style.backgroundColor = getRandomColor();
style.top = percentages[0] + "%";
style.left = percentages[3] + "%";
start = new Date().getTime(); // saves time when shape is created
console.log(width);
console.log(getRandomColor());
console.log(shapeRand);
console.log(percentages);
}
function displayShapeDelay () { // calls the main function with a delay between ]0s,2s[
setTimeout(displayShape, Math.random() * 2000);
}
document.getElementById('stop').onclick = function() {
}
}
Before I had this:
My goal was to return var 'time' to the global scope, so that I could use it to create an array of each value created with each click. I've realised that this was not possible from an anonymous function.
document.getElementById('shape').onclick = function() { // calls the delay function
style.display = "none";
displayShapeDelay();
end = new Date().getTime();
time = (end - start)/1000 ;
document.getElementById('timeBox').innerHTML = time + 's';
return time
}
So this is the code I have now :
var shapeClick = document.getElementById('shape');
shapeClick.addEventListener("click", a, false);
shapeClick.addEventListener("click", b, false);
function a() {
style.display = "none";
displayShapeDelay(); // calls the delay function
}
function b() {
end = new Date().getTime(); // saves time when clicked
var time = (end - start)/1000 ; // calculates interval from shape creation until click
document.getElementById('timeBox').innerHTML = time + 's';
return time;
}
document.getElementById('testbox').innerHTML = b();
Now, there's a couple of issues with this:
1- I can't seem to understand why the two "time divs" are assigned values after pressing the Start button. This means that function b is running, but shouldn't it only be running after the onClick event?
2- In the 'first-round' I understand why both values show up as NaN, since there's no value assigned to the variable "time" yet. But after the onClick event executes, the 'time' value assigned inside 'timeBox' works fine, but the one called outside the function doesn't. Isn't "return time" inside function b, supposed to be returning the value of the "time" variable?
Thanks in advance!
Pastel Land
The onclick function is serving as the outer function of a whole lot of code which execute when the start button is clicked. Also all of it runs every time the start button is clicked: click start multiple times quickly to see a problem. .
Inside #start.onclick() you have
document.getElementById('testbox').innerHTML = b();
in mainline click handler code: it is not inside another function and runs when the start button is clicked. Since end has not been set yet, the result for time is NaN. The code inside function b set the content of #timebox as well.
If you run the code in strict mode the javascript engine will tell you that end has not been declared. It should be - even if requred in global scope.
As an aside, fyi, Date.now() avoids the need to create and discard a Date object and is equivalent to new Date().getTime().
I suggest reworking the code to move the logic of Pastel Land outside the start button click handler, and have the click handler call into the main application code as needed but only contain logic specific to the start action itself. If you want to avoid polluting global scope you can include all the code in an IIFE (immediately invoked function expression) that would serve the same scope containment provision that the click handler is currently providing. Kindly, I think the code in its current state is presenting an x-y problem :-)
The Game
A restructured version of Pastel Land is shown below for several reasons: you've had time to try it yourself, most of the code is yours and the remainder demonstrates what was meant by the suggestion. And it's a very silly game that deserves to be played!
<!DOCTYPE html>
<html>
<head>
<title>PastelLand</title>
<meta charset="utf-8">
<script>
window.addEventListener("load", function() // an IIFE
{"use strict"
// Pastel Land
var running = false;
var start = 0;
var end = 0;
var times = []; // calculating average still to do
var el, style;
function getRandomColor() {
var hex = ["#96ceb4", "#ffeead", "#ff6f69", "#ffcc5c", "#88db8b0", "#528491"];
var color = hex[Math.floor(Math.random() * 6)]; // generates integer numbers [0,5], selects indexed item from hex
return color;
}
function displayShape () {
var percentages = [];
for (var i=0; i<4; i++){ // generates a list with 4 different random integer values [5,60]
percentages.push((Math.floor(Math.random() * 61) + 5));
}
var width = (Math.floor(Math.random() * 61) + 5); // generates integer numbers [5,60]
var shapeRand = Math.random()
if (shapeRand < 0.3) { // circle
style.borderRadius = "50%";
} else if (shapeRand >= 0.3 && shapeRand < 0.6) { // random shape
style.borderTopLeftRadius = percentages[0] + "%";
style.borderBottomRightRadius = percentages[1] + "%";
style.borderTopRightRadius = percentages[2] + "%";
style.borderBottomLeftRadius = percentages[3] + "%";
} else { // square
style.borderRadius = "0%";
}
//general shape styles
style.width = width + "px";
style.height = width + "px";
style.position = "absolute"
style.display = "block";
style.backgroundColor = getRandomColor();
style.top = percentages[0] + "%";
style.left = percentages[3] + "%";
start = Date.now(); // saves time when shape is created
console.log(width);
console.log(getRandomColor());
console.log(shapeRand);
console.log(percentages);
}
function displayShapeDelay () { // calls the main function with a delay between ]0s,2s[
setTimeout(displayShape, Math.random() * 2000);
}
function readyAlert() {
document.getElementById('readyContainer').style.display = 'none';
}
function userFound() {
style.display = "none";
end = Date.now();
var time = (end - start)/1000 ; // calculates interval from shape creation until click
document.getElementById('timeBox').innerHTML = time + 's';
displayShapeDelay(); // calls the delay function
times.push( time); // saves time user took to find shape
}
function userStart() {
if( running)
return;
running = true;
document.getElementById('readyContainer').style.display = 'block';
document.getElementById('readySeconds').innerHTML = '3'
setTimeout(function() {document.getElementById('readySeconds').innerHTML = '2'}, 1000);
setTimeout(function() {document.getElementById('readySeconds').innerHTML = '1'}, 2000);
setTimeout(readyAlert,3000);
setTimeout(displayShape, 3000);
times.length = 0; // reset times array
}
function userStop() {
running = false;
style.display="none"
}
function init() {
el = document.getElementById('shape');
style = el.style;
el.addEventListener("click", userFound, false);
document.getElementById('start').onclick=userStart;
document.getElementById('stop').onclick=userStop;
}
return init; // window load listener
}());
</script>
</head>
<body>
<div id='header'> <h1> Pastel Land </h1> </div>
<div id='container'>
<div id='readyContainer'>
<h3> This game will start in </h3>
<h1 id='readySeconds'> </h1>
</div>
<div id='shape' style="height:40px;width:40px;"></div>
</div>
<div id='features'>
<button id='start'> START </button>
<button id='stop'> STOP </button>
<p id='timeBox'></p>
<p id='timeAverageBox'></p>
</div>
<div id='testbox'> </div>
</body>
</html>
Calculation and display of averages and minor changes to page presentation remain to be done (I'm not coding them!). Units for width and height were changed from "%" to "px" (pixels) and "position: absolute;" added to shape.style. Functions a and b were combined into function userFound. Code involving "testbox" was omitted. The IIEF returns an initialization function to be executed after window load.
Notes
userStart and userStop click event handlers were defined using named function declarations instead of coding them as anonymous functions in the parameter lists of calls to other functions.
Declared function names refer to the function object created by their declaration. Hence setting the value of an element's onclick attribute to a function name works because the attribute requires a function object value. Setting onclick to the undefined value returned from calling one of the handlers would not work.
The start/stop handlers could have been registered as "click" event listeners, using addEventListener instead of element onclick values.
The init function is not called by the IIFE. The IIFE itself is called when the
window.addEventListener("load", function() { // IIFE code }() );
statement is executed in the head section of the page. All function objects declared at top level within the IIFE are created at this time. The function returned by the IIFE, init, is registered as a listener for later execution, after all DOM elements have been created for the HTML body and the window load event fires.
If you call userStart from init after other el and style have been initialized, the game will start. Although userStart is normally called in response to clicking the start button, it will still behave the same if called by other means.

How to insert pause in speech synthesis with grammatical hints

I am writing a simple spelling test app using the HTML5 SpeechSynthesis API. The text I would like my app to say is something like the following: "The spelling word is Cat. The cat chased the dog.".
The API tends to race without much of a pause from the first sentence to the second. I wonder if there is a way to insert a bit of a pause between the 2 sentences. I realize I could create 2 separate utterances and use the pause() call. However the code would be simpler and less brittle if I could simply insert grammatical hints.
Normally in spoken English, one tends to pause a little longer between paragraphs. So I inserted a newline character in my text, but there was no noticeable impact.
I also tried using an ellipsis.
Is there any way to do this or am I stuck breaking everything into separate utterances?
Using an exclamation point "!" adds a nice delay for some reason.
You can chain them together with periods to extend the pause.
"Example text! . ! . ! . !"
Split your text using comma (or custom delimiter) and add your own space using a timeout.
Here is a simple example as a proof-of-concept. Extending it, you can customize your text to include hints as to how long to pause.
function speakMessage(message, PAUSE_MS = 500) {
try {
const messageParts = message.split(',')
let currentIndex = 0
const speak = (textToSpeak) => {
const msg = new SpeechSynthesisUtterance();
const voices = window.speechSynthesis.getVoices();
msg.voice = voices[0];
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = .1; // 0 to 2
msg.text = textToSpeak;
msg.lang = 'en-US';
msg.onend = function() {
currentIndex++;
if (currentIndex < messageParts.length) {
setTimeout(() => {
speak(messageParts[currentIndex])
}, PAUSE_MS)
}
};
speechSynthesis.speak(msg);
}
speak(messageParts[0])
} catch (e) {
console.error(e)
}
}
function run(pause) {
speakMessage('Testing 1,2,3', pause)
}
<button onclick='run(0)'>Speak No Pause</button>
<button onclick='run(500)'>Speak Pause</button>
<button onclick='run(1000)'>Speak Pause Longer</button>
Just insert
<silence msec="5000" />
in the text for 5 sec waiting (Source).
Disclaimer: This code works only in an appropriate user agent.
// code taken from https://richjenks.com/dev/speechsynthesis/
var utterance = new SpeechSynthesisUtterance(),
speak = document.getElementById("speak"),
text = document.getElementById("text");
// Delay links and events because speechSynthesis is funny
speechSynthesis.getVoices();
setTimeout(function () {
// Add event listeners
var voiceLinks = document.querySelectorAll(".voice");
for (var i = 0; i < voiceLinks.length; i++) {
voiceLinks[i].addEventListener("click", function (event) {
utterance.voice = speechSynthesis.getVoices()[this.dataset.voice];
});
}
}, 100);
// Say text when button is clicked
speak.addEventListener("click", function (event) {
utterance.text = text.value;
speechSynthesis.speak(utterance);
});
<textarea id="text" rows="5" cols="50">Hi <silence msec="2000" /> Flash!</textarea>
<br>
<button id="speak">Speak</button>
I’ve found inserting synthetic pauses using commas to be quite useful (as an making other manipulations). Here’s a little excerpt:
var speech = new SpeechSynthesisUtterance(),
$content = document.querySelector('main').cloneNode(true),
$space = $content.querySelectorAll('pre'),
$pause_before = $content.querySelectorAll('h2, h3, h4, h5, h6, p, li, dt, blockquote, pre, figure, footer'),
$skip = $content.querySelectorAll('aside, .dont_read');
// Don’t read
$skip.forEach(function( $el ){
$el.innerHTML = '';
});
// spacing out content
$space.forEach(function($el){
$el.innerHTML = ' ' + $el.innerHTML.replace(/[\r\n\t]/g, ' ') + ' ';
});
// Synthetic Pauses
$pause_before.forEach(function( $el ){
$el.innerHTML = ' , ' + $el.innerHTML;
});
speech.text = $content.textContent;
The key is to clone the content node first so you can work with it in memory rather than manipulating the actual content. It seems to work pretty well for me and I can control it in the JavaScript code rather than having to modify the page source.

How to get dialogue to change upon clicking on an image?

I'm trying to create a game with dialogue, and I want my text to change as the player clicks on a next image to progress the story.
For example:
Page loads - "Hi, I'm Joe."
Clicks sliced Image once - "Nice to meet you."
Clicks 2nd time - "How are you?"
I have tried onClick but that only allows me to change it once, I've tried using var counter as well but to no avail, it overrides my previous commands, which part of this am I doing wrong here?
var clicks = 0;
function changeText() {
{
clicks = 1;
document.getElementById('text').innerHTML = "Ughh... my head... What
happened...?";
}
}
function changeText() {
{
clicks = 2;
document.getElementById('text').innerHTML = "Testing 1 2 3";
}
}
function play() {
var audio = document.getElementById("audio");
audio.play();
}
<img onClick="changeText(); audio.play()" value=Change Text src="images/awaken/images/awaken_03.jpg" alt="" width="164" height="77" id="clicks" />
<p id="text">Where... am I...?</p>
First off all - your changeText() system is flawed - you're overwriting the same function multiple times at the same time, so the only one of those that will ever get called is the last one you declare. JavaScript doesn't wait until a function gets called to continue with the program.
The audio.play() also won't work - but I'm assuming that's a work in progress.
I changed your code so that instead of setting count to a specific value, it increments every time the function gets called, and it updates the text to the correct value in an array. Here's the updated changeText function:
var count = 0;
var text = [
"Where... am I...?", /* note that this will never get called, it's simply here for filling up the array*/
"This is the first text!",
"And this is the second!"
]
var changeText = function() {
count++;
document.getElementById('text').innerHTML = text[count];
}
In the future, you'll probably also want to check if(text[count] != 'undefined'), and if so write something like "Bye!" instead.
Issues in your code
Multiple function declaration of changeText()
Extra {} in changeText()
You are not updating value of clicks.
In your html, you have written audo.play() but no audio object is available. It should be play(). I have called play() function in changeText() function. This keeps HTML clean.
Following is updated code:
var clicks = 0;
function changeText() {
var text = ""
clicks++;
switch(clicks){
case 1: text = "Ughh... my head... What happened...?";
break;
case 2: text = "Testing 1 2 3";
break;
}
document.getElementById('text').innerHTML = text;
play();
}
function play() {
var audio = document.getElementById("audio");
audio.play();
}
<img onClick="changeText()" value=Change Text src="images/awaken/images/awaken_03.jpg" alt="" width="164" height="77" id="clicks" />
<p id="text">Where... am I...?</p>

Im designing a chess game in HTML,i want to change one charecter from on position to another

i have designed chess board using buttons.Initially all the values on the button will be null,upon loading the page all the pieces appear on them and the piece of code is as follows
<input type="button" id="A8" value="" style="background:#FFE4C4;font-size: 70px;height:90;width:100" onclick="check(this.id)">
and in the onLoad function,the ASCII charecter of the chess pieces are assigned as follows:
document.getElementById('A1').value=String.fromCharCode(9814);
Now what i want is to change the one piece from a button to another on clicking two buttons.i had tried a lot with the following script
function check(clicked_id) {
var Button_2 = "";
if (i < 2) {
i++;
// alert("i:"+i);
if (i == 1) {
Button_1 = clicked_id;
B1_val = document.getElementById(Button_1).value;
alert("B1 Button val:" + B1_val);
}
if (i == 2) {
var Button_2 = clicked_id;
B2_val = document.getElementById(Button_2).value;
alert("b1 val:" + B1_val);
alert("B2 val:" + B2_val);
B2_val = B1_val;
B1_val = "";
alert("B1 val:" + B1_val + "B2 val:" + B2_val);
}
} else {
alert("Only 2 butons should press..i:" + i);
i = 0;
}
// alert("clcked a button:"+clicked_id);
}
But the code is not working
If you just want to move the value from the location of the first click to the location of the second click, then you can do that fairly simply like this:
var lastClick;
function check(id) {
var src, dest;
if (!lastClick) {
// no previous click so just store the location of this first click
lastClick = id;
} else {
// move value from lastClick id to new id
src = document.getElementById(lastClick);
dest = document.getElementById(id);
dest.value = src.value;
src.value = "";
lastClick = null;
}
}
I assume that a real application would need all sorts of error handling that doesn't let you put a piece on top of another piece, ignores first clicks on empty spaces, enforces only legal moves, etc...

Categories

Resources