I have this piece of Javascript. It works with sockets.io and server-side Node.js. Here it gets an array of data from the server and displays it on the screen.
socket.on('score', function(score) {
//"score" is an array of things to be displayed on the client
$('#scoreb').html(score[0]);
$('#scoreb_total').html(score[2]);
$('#scorer').html(score[1]);
$('#scorer_total').html(score[3]);
if(score[5] != "N"){
//find this seat's chair on this client's screen
var ch = findChair(score[4]);
$('#player'+ch+'_trump').html("Victory!");
}
});
score
is something like [40, 0, 40, 0, 3, "H"]
(using console.log
confirms that it's properly formatted).
findChair
does some calculations and returns a number between 1 and 4. If I put console.log(ch)
after the function is called, I get 1
(correct).
The code before the if
condition works fine.
And now comes the weird part. I have this in my HTML:
<div id="player1_trump"></div>
<div id="player2_trump"></div>
<div id="player3_trump"></div>
<div id="player4_trump"></div>
So after ch
is initialized, the appropriate div
(in this case player1_trump
) should be filled with the word Victory!
. But this doesn't happen! Weirder still, when instead of console.log
I use alert
here:
var ch = findChair(score[4]);
alert(ch);
$('#player'+ch+'_trump').html("Victory!");
When I click 'OK' on the alert prompt, the word Victory is displayed correctly in player1_trump
! So what's going on here? There's nothing asynchronous here, this is plain client-side Javascript, and ch
is apparently correct after the findChair
function runs. So why does it only work when I put an alert between one line and the other?
EDIT (here is the function):
function findChair(s){
var ch = -1;
$.each(chairs, function (chair, seat) {
if(s == seat)
ch = chair;
else
$('#player'+chair+'_trump').html('');
});
return ch;
}
EDIT 2:
If I replace $('#player'+ch+'_trump').html("Victory!");
with document.getElementById('#player'+ch+'_trump').innerHTML="Victory!"
I get an error saying TypeError: document.getElementById(...) is null
. However, if I look at the source code before any of this happens (it all happens when a button is clicked, not on page load) the target div is present.
Using $('#player'+ch+'_trump').delay(200).html("Victory!");
also doesn't work, regardless of how long a delay I put in it. So it's not just a matter of timing.
Using .text
instead of .html
also doesn't work.