-3

I need to run javascript only once, save to cookies, then, when try to execute function, check if cookies saved, if so, don't trigger function.

I'm sure this script has an error because it doesn't do what I need :

var prom = getCookie('prom');
if (prom === null || prom === '0') 
{
if (document.getElementById('tst')){
    var str=document.getElementById("tst").innerHTML;
    var n=str.replace("Login","Logout");
    document.getElementById("tst").innerHTML=n;
    setCookie("prom",'1',1);
}
}

Html code where script triggers to change 'Login' in 'Logout'

<a href="login"  title="log in" class="login_button" id="tst">Login</a></span>

Cookies script :

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    if (exdays) exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays) ? '; expires=' + exdate.toUTCString() : '');
    document.cookie = c_name + "=" + c_value;
}

function getCookie(name) {
    var re = new RegExp(name + "=([^;,]+)");
    var value = re.exec(document.cookie);
    return (value !== null) ? unescape(value[1]) : null;
}

Jsfiddle test if http://jsfiddle.net/8yZaP/11/

marius
  • 329
  • 1
  • 2
  • 16

1 Answers1

6

Change

if (prom = '0'){

To

if (prom === '0'){

(Of course, assuming getCookie and setCookie persist similar to sessionStorage).

jedwards
  • 29,432
  • 3
  • 65
  • 92
  • 2
    You should always use identity operators (`===`), not comparison operators (`==`) in javascript. [Related question](http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use) – jbabey Apr 05 '13 at 19:58
  • @jbabey, +1 good point -- thanks – jedwards Apr 05 '13 at 19:59
  • Strange, now it doesn't trigger the function. On console error: ReferenceError: "prom is not defined" if(prom === '0'){ – marius Apr 05 '13 at 20:09
  • From your edit, you need to assign the return value of `getCookie()` to something: eg `var prom = getCookie('prom');` – jedwards Apr 05 '13 at 20:12
  • I made the modifications. No more errors on console but script still did't trigger. Also On Resources-Cookies- no event for 'prom'. If I remove if (prom === '0') function is executed. – marius Apr 05 '13 at 20:23
  • Please check this Jsfiddle http://jsfiddle.net/8yZaP/11/ , if you remove if (prom === '0') script/cookies work. – marius Apr 05 '13 at 20:58
  • http://jsfiddle.net/JBFFn/8/ seems to work. – jedwards Apr 05 '13 at 21:12