Solved

How do I create a JavaScript Cookie for a specific JavaScript event within a webpage?

Posted on 2008-06-11
22
274 Views
Last Modified: 2010-04-21
I am a website designer but have never used cookies before.

As such I need to learn how to create a very basic cookie that will determine an open or closed state for a JavaScript-based spry widget in DreamWeaver.

I want this particular widget to be set to open automatically ONLY on a person's first visit to the website ONCE per day, but subsequent visits to the site within a specific amount of time will not cause this widget to be automatically open on load.

I would think this is similar to the cookies that control whether a pop-up window opens everytime someone goes to a homepage rather that only once per day, but I cannot figure out how to use such scripting for the spry widget.

Here's a link to the page in question: http://www.bonesvillemedia.com/pirateclub-v3/index.html

The item I'm wanting to control with a JavaScript cookie is the collapsible panel at the top of the page. (Right now I'm avoiding having it open on every return visit to the homepage by using a nearly identical page, index2.html as the homepage link from within the site. The difference is index2.html uses a template which doesn't have the panel set to open by default.)

Thanks in advance!

Sara
0
Comment
Question by:EmeraldIsleNC
  • 13
  • 9
22 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21766947
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21766966
and try

document.getElementById('HomePageAnnouncement').click()
0
 

Author Comment

by:EmeraldIsleNC
ID: 21768929
Ok... I wasn't sure how to use the line of code you gave me or exactly what part of that website I was supposed to look to for answers. (I had seen a few cookie sites already, but naturally being under the gun with a deadline, I didn't have time to read through all of the sites to try to make sense of what to do, and I had hoped to get some help here from people who have vastly more knowledge than I do about this topic and save myself some much-needed development time. LOL)

That said, I did follow links from the site you suggested and came upon a page about creating a cookie to display a welcome page to new visitors to the site.

I modified the script that I found to have it do essentially the same thing, but calling upon the spry widget. Unfortunately, I'm getting an error in IE with the javascript and it is saying that "AnnouncementPanel" is undefined when that's what I've named the cookie. Please see script below to see if the syntax is ok and if it seems like it can do what I'm hoping.

The second chunk of script is what usually appears in the Dreamweaver page depending on whether the widget is set to be automatically open when someone arrives to the page, or automatically closed.

Thanks so much for your time and help!!!

Sara
<!-- HERE'S THE SCRIPT AS I MODIFIED IT TO CALL UPON THE WIDGET DEPENDING ON THE PRESENCE OF THE COOKIE -->
 

<script type="text/javascript">

<!--

var expdate = new Date();

expdate.setTime(expdate.getTime() +  (60 * 60 * 12)); 

var cookieName = "AnnouncementPanel";        

    if (getCookie(AnnouncementPanel) == null || getCookie(AnnouncementPanel) == "true") {

    setCookie(AnnouncementPanel, "true", expdate);

		var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement");

    }

    else if (getCookie(AnnouncementPanel) == "offtemp") {

    setCookie(AnnouncementPanel, "true", expdate);

	var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement", {	contentIsOpen:false});

    }

//-->

</script>
 

<!-- END OF THIS SCRIPT -->
 

<!-- REGULAR DREAMWEAVER CODE IF WIDGET IS TO BE OPEN BY DEFAULT -->
 

<script type="text/javascript">

<!--

var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement");

//-->

</script>
 

<!-- END OF THIS SCRIPT -->
 

<!-- REGULAR DREAMWEAVER CODE IF WIDGET IS TO BE CLOSED BY DEFAULT -->
 

<script type="text/javascript">

<!--

var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement", {contentIsOpen:false});

//-->

</script>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21769491
var cookieName = "AnnouncementPanel";         // sets the variable name cookieName to contain the name of the cookie
    if (getCookie(cookieName) == null || getCookie(cookieName) != "true") { // uses the new variable and sets cookie if not set or NOT true
    setCookie(cookieName, "true", expdate);
                var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement");
    }
    else if (getCookie(cookieName) == "offtemp") {
    setCookie(cookieName, "true", expdate);
        var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement", {      contentIsOpen:false});
    }

0
 

Author Comment

by:EmeraldIsleNC
ID: 21769761
Ok... I see my mistake as it relates to changing the instances of "cookieName" to the actual name "Announcement Panel."

I've applied these changes, but now I'm getting a new error.

It's at line 355 char 5.

Here's the link: http://www.bonesvillemedia.com/pirateclub-v3/

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21769833
erm where is the
cookie.js ???
// cookie.js file

var cookieToday = new Date(); 

var expiryDate = new Date(cookieToday.getTime() + (365 * 86400000)); // a year
 

/* Cookie functions originally by Bill Dortsch */
 

function setCookie (name,value,expires,path,theDomain,secure) { 

   value = escape(value);

   var theCookie = name + "=" + value + 

   ((expires)    ? "; expires=" + expires.toGMTString() : "") + 

   ((path)       ? "; path="    + path   : "") + 

   ((theDomain)  ? "; domain="  + theDomain : "") + 

   ((secure)     ? "; secure"            : ""); 

   document.cookie = theCookie;

} 
 

function getCookie(Name) { 

   var search = Name + "=" 

   if (document.cookie.length > 0) { // if there are any cookies 

      var offset = document.cookie.indexOf(search) 

      if (offset != -1) { // if cookie exists 

         offset += search.length 

         // set index of beginning of value 

         var end = document.cookie.indexOf(";", offset) 

         // set index of end of cookie value 

         if (end == -1) end = document.cookie.length 

         return unescape(document.cookie.substring(offset, end)) 

      } 

   } 

} 

function delCookie(name,path,domain) {

   if (getCookie(name)) document.cookie = name + "=" +

      ((path)   ? ";path="   + path   : "") +

      ((domain) ? ";domain=" + domain : "") +

      ";expires=Thu, 01-Jan-70 00:00:01 GMT";

}

Open in new window

0
 

Author Comment

by:EmeraldIsleNC
ID: 21769889
Wow! Thanks for that! I didn't even see any mention of that on the page where  originally found that script.

And as I mentioned, this is not my area of expertise (at all!)

Let me put this in place and see if this clears up the errors... and then my last question will be:

Does the expiration date at the end of this cookie.js file interfere with the fact that I want the cookie to only last 8 hours? If it does, what syntax would I use in the *.js file to make the cookie expire after 8 hours?

Thanks! You're awesome for helping me!
0
 

Author Comment

by:EmeraldIsleNC
ID: 21769908
Wait.... I see the bit at the top about the expiration date, as well... so I know how to change that part. It's the expire at the bottom that I wasn't sure about.
0
 

Author Comment

by:EmeraldIsleNC
ID: 21769926
And lastly, is the amount mentioned for the expiryDate measured in seconds? (In other words, could I just change that part to 28800 to equal 8 hours?)
0
 

Author Comment

by:EmeraldIsleNC
ID: 21770007
By the way, this is where I found the script I modified and used:

http://www.webreference.com/javascript/961125/part03.html

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21770152
Milliseconds

Please change your

expDate
to
expiryDate
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:EmeraldIsleNC
ID: 21770256
Ok... that's done... new error now. Line 356.

I'm thinking there's not agreement between the cookie name in index.html and the cookie name in the cookie.js file (which I've placed in the root folder).

I have no idea how to fix that.
0
 

Author Comment

by:EmeraldIsleNC
ID: 21772097
I've done away with the whole cookie idea for now. I've just gotten too close to my deadline and I've had to come up with a workaround that doesn't involve cookies.

I'll probably revisit this at some point in the near future, but for now the link I gave you will no longer be applicable as I've removed the script.

Thanks for trying to help me with this.

Sara
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21777003
Ok, good luck
0
 

Author Comment

by:EmeraldIsleNC
ID: 21782589
Ok... I couldn't keep away from working on this. I've created a new index3.html as a test page for this cookie and I think I've solved part of the problem.

Near the top of the code for my page, the Spry Collapsible Panel is called by using the following script. (See below.)

I've moved the script we discussed yesterday into a seperate *.js file and called it in the body of the page instead of having the script entirely written there.

So... my question is, how do I move the two lines of code below out of the actual page and into the CollapsiblePanelCookie.js file that I've created, or if that's not what I should do, what else would you recommend I do to keep this from creating a conflict since it won't work the way it is now?

Here is a link to the live page:

http://www.bonesvillemedia.com/pirateclub-v3/index3.html

Thanks!

Sara
Here are the two lines of code that I'm not sure what to do with:
 

<script src="../SpryAssets/SpryCollapsiblePanel.js" type="text/javascript"></script>

<link href="../SpryAssets/SpryCollapsiblePanel.css" rel="stylesheet" type="text/css" />
 

==========================================
 

Here is where I call on the script in my page (in place of where the DreamWeaver code was that called on the script): [Note: The menubar bit is the DreamWeaver code for calling on my menubar information. That is where DreamWeaver originally called on my collapsible panel.
 

==========================================
 

<script src="../scripts/CollapsiblePanelCookie.js" type="text/javascript"></script>
 

<script type="text/javascript">

<!--

var MenuBar2 = new Spry.Widget.MenuBar("MenuBar2", {imgRight:"/pirateclub-v3/SpryAssets/SpryMenuBarRightHover.gif"});

//-->

</script>

</body>

</html>
 
 

==========================================
 

I've moved the following script out of the index3.html page and into its own .js file in my scripts folder called CollapsiblePanelCookie.js:
 

==========================================
 

// JavaScript Document

// CollapsiblePanelCookie.js file

var expiryDate = new Date();

expiryDate.setTime(expiryDate.getTime() +  (60 * 60 * 8 * 1000)); 

var cookieName = "AnnouncementPanel";         // sets the variable name cookieName to contain the name of the cookie

    if (getCookie(cookieName) == null || getCookie(cookieName) != "true") { // uses the new variable and sets cookie if not set or NOT true

    setCookie(cookieName, "true", expiryDate);

                var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement");

    }

    else if (getCookie(cookieName) == "offtemp") {

    setCookie(cookieName, "true", expiryDate);

        var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement", {      contentIsOpen:false});

    }
 

==============================================
 

The following is the code you so kindly provided that should be my cookie.js file:
 

==============================================
 

// JavaScript Document

// cookie.js file

var cookieToday = new Date(); 

var expiryDate = new Date(cookieToday.getTime() + (60 * 60 * 8 * 1000)); // 8 hours

 

/* Cookie functions originally by Bill Dortsch */

 

function setCookie (name,value,expires,path,theDomain,secure) { 

   value = escape(value);

   var theCookie = name + "=" + value + 

   ((expires)    ? "; expires=" + expires.toGMTString() : "") + 

   ((path)       ? "; path="    + path   : "") + 

   ((theDomain)  ? "; domain="  + theDomain : "") + 

   ((secure)     ? "; secure"            : ""); 

   document.cookie = theCookie;

} 

 

function getCookie(Name) { 

   var search = Name + "=" 

   if (document.cookie.length > 0) { // if there are any cookies 

      var offset = document.cookie.indexOf(search) 

      if (offset != -1) { // if cookie exists 

         offset += search.length 

         // set index of beginning of value 

         var end = document.cookie.indexOf(";", offset) 

         // set index of end of cookie value 

         if (end == -1) end = document.cookie.length 

         return unescape(document.cookie.substring(offset, end)) 

      } 

   } 

} 

function delCookie(name,path,domain) {

   if (getCookie(name)) document.cookie = name + "=" +

      ((path)   ? ";path="   + path   : "") +

      ((domain) ? ";domain=" + domain : "") +

      ";expires=Thu, 01-Jan-70 00:00:01 GMT";

} 

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21784390
But you did not include the cookie.js in the page... (or put the cookie code in the CollapsiblePanelCookie.js )

I would not put the spry code in the js file I think...
0
 

Author Comment

by:EmeraldIsleNC
ID: 21786535
Ok... I'm no longer getting a javascript error on the page and that's a good thing. I moved that CollapsiblePanelCookie.js script back into the body of the page. I referenced the cookie.js in the header of the page.

Problem is, now that I'm not getting any errors you'd think everything is working great, but the collapsible panel won't close. Furthermore, the cookie seems to be completely ineffective because everytime I return to the page the collapsible panel seems stuck open.

For much I'd see what you'd charge me to go ahead and help me finish troubleshooting this. I see on your page that you do elance work.

Let me know.

Thanks!

Sara

0
 

Author Comment

by:EmeraldIsleNC
ID: 21786537
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 21787656
Ok, I think I understand now - it is quite early so it could be I got the test the wrong way around. Try to grasp what I have done...

1. change this
<div align="center">+/- (CLICK HERE TO OPEN/CLOSE THIS PANEL)</div>
to this
<div align="center"
onClick="var cook = getCookie('AnnouncementPanel');
if (cook==null || cook =='panelOpen' ) setCookie('AnnouncementPanel','panelClosed',expiryDate)">+/- (CLICK HERE TO OPEN/CLOSE THIS PANEL)</div>

2. replace the last two script tags with attached. It should show the open panel when there is no cookie

<script type="text/javascript"><!-- 

var cook = getCookie("AnnouncementPanel"); // get the cookie       

if (cook == null || cook != "panelClosed") {  

  setCookie(cookieName, "panelOpen", expiryDate);

  var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement", {contentIsOpen:true});

}

else if (cook == "panelClosed") {

  var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("HomePageAnnouncement", {contentIsOpen:false});

}

var MenuBar2 = new Spry.Widget.MenuBar("MenuBar2", {imgRight:"/pirateclub-v3/SpryAssets/SpryMenuBarRightHover.gif"});

//-->

</script>

Open in new window

0
 

Author Comment

by:EmeraldIsleNC
ID: 21789112
You are a genius! Thank you so much for helping me solve this problem! I can't tell you what a huge relief this is.

The only thing I had to fix from that last bit of script you gave me was from line 4. (See code below.)

Thanks again!

Sara
For code line 4

you wrote:
 

  setCookie(cookieName, "panelOpen", expiryDate);
 
 

I had to fix it to say:
 

  setCookie(cook, "panelOpen", expiryDate);

Open in new window

0
 

Author Closing Comment

by:EmeraldIsleNC
ID: 31466279
THANK YOU! THANK YOU! THANK YOU!!!!
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21789126
You are welcome!

Sorry about the typo
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now