JavaScripter
JavaScripter

Reputation: 4842

variable scope issue with javascript

In my application, originally those codes works:

var htm = "<div> My content </div>";   
$("#divprint").html(htm);
window.setTimeout('window.print()', 4000);

however, when I try to wrap it within an if statement, it won't print:

var canprint= $.cookie("actionprint");  
alert("I am outside " + canprint);
if(canprint == null){
    alert("I am inside");
    var htm = "<div> My content </div>";
    window.setTimeout('window.print()', 4000);
}

when I run this codes, I only got first alert: "I am outside null"

As javascript's scope is function level, I am wondering, why that if failed?

Upvotes: 0

Views: 104

Answers (3)

JavaScripter
JavaScripter

Reputation: 4842

OK. As weird it is:

Firstly, I tried to print out:

  console.log(typeof canprint, canprint);

amazingly, result is:

string null

so, I changed to if condition to:

if(canprint == "null")

then it can goes inside that if.

Though this is working, does anyone who can explain what has happened? This is really out of my expedition.

Upvotes: 1

vasudevanp
vasudevanp

Reputation: 215

Can you try the if statement like,

if (!canprint)

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Remove the quote and parenthesis from setTimeout function

window.setTimeout(window.print, 4000);

And use something like this: jQuery check if Cookie exists, if not create it

var CookieSet = $.cookie('cookietitle', 'yourvalue');

     if (CookieSet == null) {
          // Do Nothing
     }
     if (jQuery.cookie('cookietitle')) {
          // Reactions
     }

Upvotes: 0

Related Questions