Read cookie and show/hide div

Hello,

I am having great difficulty writing a simple script that detects a cookie and either hides or displays a piece of content depending on whether that cookie has been set.

I have read through a few posts and JS tutorials but but unfortunately I am a complete JavaScript novice (although novices probably have more JS skills than I :slight_smile: ) so am struggling to follow the tutorials and instructions provided. :blush:

So I am (wishful thinking?) hoping that someone will take a few mins to spoon feed me the code I need for the functionality I described above :shifty:


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;
}

function setCalendar(){

	var region = readCookie("region");

	if (region == null){
		document.getElementById("monkey").style.display = "block";
	}
	else {
		document.getElementById("monkey").style.display = "none";
	}
 }




<body onload="setCalendar();">

<div id="monkey">Cookie</div>

noone able to help me with this? Or link to a tutorial, script with similar functionlaity? :frowning:

What you have there seems to be working so far.

The question is, under what circumstances is the region variable going to be set so that the div will be hidden?

The code I posted actually doesn’t work at all, which is why I assumed I’m on the wrong track.

The region cookie is set by a php script on a separate page. If the region cookie has been set, the div will display a region specific message. If the resgion cookie is not set, the div will display a link to the php form.

When testing I’ve used the quirksmode cookie handling functions to set the “region” cookie and found that the code worked as expected, hiding the div when the cookie exists.

Are you sure that the php script is properly setting the cookie?


// If the form has been submitted, process it
if (isset($_POST['view_region'])) {

	// first delete any existing region cookies
	setcookie("region", "", time()-3600);

	
	// now set the new coookie
	setcookie("region", $_POST['region_select'], time()+6000);

	// and redirect to the calendar page
	header('Location: index.htm');
}



// If the form hasn't been submitted, display it
else {

:blush: I realise this isn’t a PHP forum but the above code is creating the cookie correctly as I have a 2nd PHP script to test it.

Have you looked at your local cookie text file to see what actual cookie information is there?

I’m working from a locked down system, no access to cookie files. Just not sure why the php scripts would be working for the same cookie if there was something wrong with the cookie file itself?

Would you mind providing the code you used to test my script? Perhaps I’m missing something

ok this a quite a steep learning curve for me but I am making progress. The below code works in Firefox and Opera but not in IE.


<script type="text/javascript">
<!--
/* COOKIES */
var Cookies = {
	init: function () {
		var allCookies = document.cookie.split('; ');
		for (var i=0;i<allCookies.length;i++) {
			var cookiePair = allCookies[i].split('=');
			this[cookiePair[0]] = cookiePair[1];
		}
	},
	create: function (name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
		this[name] = value;
	},
	erase: function (name) {
		this.create(name,'',-1);
		this[name] = undefined;
	}
};
Cookies.init();

function saveIt(name) {
	var x = document.forms['cookieform'].events_region.value;
	if (!x)
		alert('Please select your region.');
	else {
		Cookies.create(name,x,7);
		return true;
	}
}

function readIt(name) {
	alert('The value of the cookie is ' + Cookies[name]);
}

function eraseIt(name) {
	Cookies.erase(name);
}

/* Validation */
function validate() {
if (document.getElementById('events_region').selectedIndex == 0 ) {
		alert("Please select a region");
		document.getElementById('events_region').focus();
		return false;
	}
}

// -->
</script>

<script type="text/javascript">
function setCalendar(){

    var whatsonRegion = readCookie('calregion');

    if (whatsonRegion == null){
        document.getElementById("eventSelect").style.display = "block";
		document.getElementById("eventRegion").style.display = "none";
    }
    else {
        document.getElementById("eventSelect").style.display = "none";
		document.getElementById("eventRegion").style.display = "block";
    }
 }
 </script>



<div id="eventSelect">
<h1>Regional Calendar</h1>
<form name="cookieform" action="/calendar/index.php"><p>
	 <select name="events_region">
		<option value="select">select your region</option>
		<option value="DS">Deep South</option>
        <option value="HN">High North</option>
        <option value="WE">Way East</option>
        <option value="FW">Far West</option>
	</select>
	<input type="submit" value="go" id="view_region" onClick="javascript:saveIt('calregion')" />
</form>
</div>

<div id="eventRegion">
<a href="/whatson/">What's on in my regoin</a>
</div>

Need help to :slight_smile: :

  1. Get this working in IE

2) Remove the cookie alert boxes without losing functionality of the form - done

  1. Display a variable (based on the cookie contents) as the show/hide div.

For example.

  • User selects region “Deep South”. Div displays “Events happening in the Deep South”.
  • User has no cookie set, div displays “Select your region”

Of course, here’s the test code that I was using.


<html>
<head>
	<title></title>
<script>
</highlight]


```javascript

createCookie("region", "here", 1);
eraseCookie("region");
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i &lt; 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;
}
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 var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
function setCalendar(){
 
    var region = readCookie("region");
 
    if (region == null){
        document.getElementById("monkey").style.display = "block";
    }
    else {
        document.getElementById("monkey").style.display = "none";
    }
}


&lt;/script&gt;
&lt;/head&gt;
&lt;body onload="setCalendar();"&gt;
&lt;div id="monkey"&gt;Cookie&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

Thanks Paul, I have implemented your code and with a bit of tweaking have achieved most of the functionality I was aiming for.

I’m wondering if you can help me with one last issue: how to set a variable based on the contents of the cookie and echo it in the monkey div.

I imagine the logic would be very similar to PHP I’m just not familiar with the javascript code I’d need:


<?php

// Change title on cookie

//throw it in a variable
$area = strtolower($_COOKIE['region']);

if ($area == "ds") {
	
	$title = "Deep South";

	}

elseif ($area == "Far West") {
	
	$title = "Deep South";

	}

else {
	
	$title = "Everywhere Else";

	}

?>

<div id="monkey">
<?php echo $title; ?>
</div>

<div id="monkey">

<script language="JavaScript">
<!-- hide from older browser
var test

if (readCookie('region) == "ds") {

	test = "Sup Cookie?!";
}

else {
test=readCookie('region')
}
document.write(test) //-->
</script>

</div>

This seems to be functioning, I’m hoping the syntax is not too incorrect :cool:

The logic is similar, but javascript is quite a different beast from php

I presume that you didn’t mean that “Far West” should be shown as “Deep South”, but instead “fw” should be shown as “Far West”.

We can set up something like a key-based array where we use the area code to get the title, showing the default area if it’s not there.

Here’s the main script that ties all of this together.


var area = readCookie('area');
replaceContentWithText(
    document.getElementById('monkey'),
    getAreaTitle(area)
);

I believe that you have a readCookie script already from Quirksmode cookie handling functions.

The other functions are self-explanatory, so here’s the code for them.


function getAreaTitle(area) {
    var defaultArea = 'Everywhere Else',
        title = {
            'ds': 'Deep South',
            'fw': 'Far West'
        };
    return title[area] || defaultArea;
}


function replaceContentWithText(el, text) {
    var textNode = document.createTextNode(text);
    while (el.hasChildNodes()) {
        el.removeChild(el.firstChild);
    }
    el.appendChild(textNode);
}

If you run the above script from the head section, you’ll need to use some kind of window.onload technique so that it can work with the page elements.

If you put the script at the bottom of the page, just before the </body> text, you won’t need any kind of onload stuff and you will also be following one of the [URL=“http://developer.yahoo.com/performance/rules.html”]best practices to speed up your web site.

Wow your code is like a lion to my kitten :lol:

I had to look up most of the code you used but I mostly understand how it works and have modified it slightly to my own needs. :slight_smile:

Thanks very much for your help Paul, very appreciated. :lman:

You’ve certainly given me more motivation to learn this language (now just to find the time :goof: )

I’ll make some comments about this posted code. It may pay to bear in mind that no harm is intended from what’s going to follow. Instead, it’s to help keep you out of harms way.

If you do ever want to get your feelings hurt then run some script code through jslint.com - that place is designed to hurt even the hardest feelings, but a lot is learned there as well.

First I’ll correct a missing aphostrophy after the word “region” so that it doesn’t screw up the syntax highlighting of the rest of the code.


<!-- hide from older browser
var test

if (readCookie('region') == "ds") {

    test = "Sup Cookie?!";
}

else {
test=readCookie('region')
}
document.write(test) //-->

The comments to hide code from older browsers are useless nowdays.


<!-- hide from older browser
...
//-->

First, the comments were to stop Netscape version 1 and Mosaic from seeing the script as page content. This was because those browsers didn’t understand javascript. Look at the version number again - Netscape version 1.

Please check out Javascript and HTML script tags by Douglas Crockford for more details.

Second, script code should not be inline on the page. That’s just as bad as having css style declared inline in the head section. For both you should refer to an external file where the script/style is stored instead. When you do that, the comments then also become useless because they apply only for inline scripts.

I hope that my point has been clearly made here.

The rest of the code needs to have end of statement semicolons, and be properly indented.

The double equals should be a triple equals instead, so that you can check that they’re actually equal. Using the double equals only checks to see if they’re kinda-sorta the same, but don’t have to be to be true. See Comparison Operators for more about the strange and weird rules therein. Avoid the potential troubles and just check if they’re actually equal by using the strict comparison operators instead.

It’s also considered to be a bad practice to use document.write too, for which you can read more about in the article on six javascript practices we do not need any longer

It equates on the scale of badness as being similar to using the font tag to style your page content. Instead of blurting out the text with document.write, you should reach out to the element that supposed to contain it and update the content inside. Even if that means using innerHTML when you’re getting started.

And finally it helps to use consistant quotes throughout the code. Because double quotes are used for HTML is has become a standard to use single quotes for javascript.

Here is an updated version of the code. Some of the variables have been renamed too in order to make it easier to understand what’s happening. For example, the readCookie function is called twice, when it can be stored in the title variable instead.


var monkey = document.getElementById('monkey');
var title = readCookie('region');
if (title === 'ds') {
    title = 'Sup Cookie?!';
}
monkey.innerHTML = title;

The reasons for some of these things is so that the code doesn’t have to be scattered about all over the place. It can be neatly kept in a separate file so that when good coding practices are applied, updates can happen to only one area at a time.

I’m still puzzled though about monkey.

I don’t mind comments Paul, I’m about as beginner as you can get in regards to JavaScript and appreciate anything that points me in the right direction. :slight_smile:

You’re welcome. It s a pleasure to be in a position to provide the help that I can give.

But what’s up about the monkey?

A bad habit from php programming. My fave testing string is not ‘hello world’ but rather ‘purple monkey washing machine’. :eyebrow: