0

I have <img id="token" src="/files/images/token.png" /> that I'm attempting to change opacity with window.onload if $tokens value is 0. the $tokens value does read correctly and displays below the image with how many there are. this is my script:

<script>
window.onload=function(){
if($tokens == '0'){
var ntoken= document.getElementById("token");
   ntoken.style.opacity='0.4';
   ntoken.style.filter='alpha(opacity=40)';
 }
}
</script>

did I forget something?

  • 2
    And where are you getting `$tokens` from ? – adeneo Mar 13 '14 at 18:17
  • @adeneo my database, i've tested it and i can go in and change the value and it will display in the sentence `You have Tokens left!` how many are currently in the database. getting the value of $tokens is working as it should. – KissingKings Mar 13 '14 at 18:19
  • $tokens is a string or a number? If later, have you tried `if (parseInt($tokens) == 0)`? – Nicolae Olariu Mar 13 '14 at 18:22

1 Answers1

2

Following @adeneo's remark, you might be mixing up PHP and javascript variables. It's a bit nasty but try this:

<script>
window.onload=function(){
if(<?php echo $tokens; ?> == '0'){
var ntoken= document.getElementById("token");
   ntoken.style.opacity='0.4';
   ntoken.style.filter='alpha(opacity=40)';
 }
}
</script>

c.f. How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

Community
  • 1
  • 1
Aegis
  • 1,749
  • 11
  • 12
  • that works...but i still don't understand why. any extra knowledge would be great. – KissingKings Mar 13 '14 at 18:24
  • if the number of tokens is 0 then you're basically saying `if(0 == 0)` (from a javascript point of view) – andrew Mar 13 '14 at 18:26
  • lol well since that's a true statement, wouldn't it still cause it to take effect? at least to me logically it would. – KissingKings Mar 13 '14 at 18:27
  • 1
    It works because of the PHP tags, you can't just stick a PHP variable in javascript, it has no meaning there. – adeneo Mar 13 '14 at 18:30
  • Yep, as @adeneo just said PHP and Javascript are two very distinct programming languages. More than that PHP is executed on the server-side and javascript on the client-side, so you can't possibly access a PHP variable from javascript code (however, you can use 'echo' to render it as a string in the javascript code...). – Aegis Mar 13 '14 at 18:44
  • @KissingKings was asking if it did evaluate to `if(0 == 0)` why wouldn't it execute anyway? The answer is it would, but it's not evaluated like that. It's actually `if(null == 0)` which would evaluate false and not run. – Samsquanch Mar 13 '14 at 18:49
  • @Samsquanch actually it won't even coerce to null, you'll get a ReferenceError (at least on chrome). – Aegis Mar 13 '14 at 18:51