views:

43

answers:

3

I am displaying a div on my site, and I want to only display this div 5 times that the user has visited my site. So after 5 times, it wont show the div anymore.

I can do it with cookies. But Im only familiar with PHP. Javascript isn't my strong side.

Does anybody have a short piece of code to set a cookie, increase it for every visit, and if value is greater than 5 then don't show the DIV anymore?

Thanks

A: 

Quirksmode has an article discussing cookies, which also includes three very handy helper functions (scroll down to the bottom). Read the article and all will become clear anyway.

Just remember that all information is stored as a string, and hence it is retrieved as a string. Therefore you should definitely be doing some manual type juggling before performing any operations on the data. See here:

var x = 1;
createCookie("myVar", x);

var newX = readCookie("myVar") + 1;

alert(newX); // "11"

// --- instead, do this: ---

var newX = parseInt(readCookie("myVar"), 10) + 1;
nickf
A: 

Nobody will have exactly the piece of code you are asking for, but it should be easy to compose it yourself, starting from these 2 necessary functions:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length,c.length);
    }
    return null;
}
cherouvim
+1  A: 

let's say you have the variable visits in the cookies, you mainly use something similar to this

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

var visits = getCookie("visits_number");

if (visists > 5)
    document.getElementById("your_div_name").setAttribute("style", "visibility: hidde");
martani_net
Don't use `setAttribute` on an HTML document. There are many bugs in it in IE, one of which is that `style` won't work. Suggest `getElementById(...).style.display= 'none'`.
bobince