[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 289
  • Last Modified:

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

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
EmeraldIsleNC
Asked:
EmeraldIsleNC
  • 13
  • 9
1 Solution
 
Michel PlungjanIT ExpertCommented:
0
 
Michel PlungjanIT ExpertCommented:
and try

document.getElementById('HomePageAnnouncement').click()
0
 
EmeraldIsleNCAuthor Commented:
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Michel PlungjanIT ExpertCommented:
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
 
EmeraldIsleNCAuthor Commented:
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
 
Michel PlungjanIT ExpertCommented:
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
 
EmeraldIsleNCAuthor Commented:
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
 
EmeraldIsleNCAuthor Commented:
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
 
EmeraldIsleNCAuthor Commented:
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
 
EmeraldIsleNCAuthor Commented:
By the way, this is where I found the script I modified and used:

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

0
 
Michel PlungjanIT ExpertCommented:
Milliseconds

Please change your

expDate
to
expiryDate
0
 
EmeraldIsleNCAuthor Commented:
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
 
EmeraldIsleNCAuthor Commented:
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
 
Michel PlungjanIT ExpertCommented:
Ok, good luck
0
 
EmeraldIsleNCAuthor Commented:
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
 
Michel PlungjanIT ExpertCommented:
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
 
EmeraldIsleNCAuthor Commented:
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
 
EmeraldIsleNCAuthor Commented:
0
 
Michel PlungjanIT ExpertCommented:
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
 
EmeraldIsleNCAuthor Commented:
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
 
EmeraldIsleNCAuthor Commented:
THANK YOU! THANK YOU! THANK YOU!!!!
0
 
Michel PlungjanIT ExpertCommented:
You are welcome!

Sorry about the typo
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 13
  • 9
Tackle projects and never again get stuck behind a technical roadblock.
Join Now