Software, your way.
burger menu icon
WillMaster

WillMasterBlog > JavaScript

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Do Only Once

This post will show how to prevent pretty much any JavaScript function from running more than once with a cookie. The instructions in the JavaScript tell how to set up to cookie to be available site-wide or only from certain directories.

The first thing to do is to put these two lines of JavaScript into the function you want to limit to running only once:

if(HasCookie()) { return; }
GiveCookie();

Make it so those two lines are the first lines the function runs. For example, if your function was

function Something()
{
   alert("hello");
}

Then it would become

function Something()
{
   if(HasCookie()) { return; }
   GiveCookie();
   alert("hello");
}

That was the first step. The above code will work only when both steps have been completed.

What the above code does: If the browser has the cookie, processing returns out of the function. Otherwise, it is given the cookie and the function continues to run.

The next step is to insert this JavaScript somewhere above the modified function.

It doesn't have to be immediately above, although it can be. The idea is for the browser to load this JavaScript before the modified function is loaded.

<script type="text/javascript" language="JavaScript">
// Copyright 2007 Bontrager Connection, LLC
// https://www.willmaster.com/
//
// Type the domain name for the cookie.
// These examples use domain name example.com. Use your own 
//    domain name instead.
// To cookie can be applied to the www.example.com and/or 
//    the example.com versions of URL. Decide which you 
//    want (or both) and specify the domain below.
//       "www.example.com" (sets cookie for 
//                          http://www.example.com/)
//       "example.com"     (sets cookie for 
//                          http://example.com/)
//       ".example.com"    (sets cookie for both 
//                          http://www.example.com/ and 
//                          http://example.com/ -- and also
//                          http://anything.example.com)

var CookieDomain = ".example.com";


// Specify the directory the cookie is set for.
// To apply the cookie to the entire domain, specify "/"
// To apply the cookie to only a certain directory (and its 
//    subdirectories), specify "/directoryname"

var CookieDirectory = "/";


// Specify the cookie name. The name may have only letters 
//    and numbers.
// The name matters only to make sure no other cookie with 
//    the same name is set for this domain and directory.

var CookieName = "myCookie";


// Specify how many days the cookie shall last. Use the 
//    number 0 to make it a session cookie (a cookie that 
//    will self-delete when the browser closes).

var DaysCookieShallLive = 365;


//
// No other customization needs to be done in this JavaScript.
//
////  ////  ////  ////

function GiveCookie() {
var d = parseInt(DaysCookieShallLive);
var exp = '';
if(d > 0) {
	var now = new Date();
	then = now.getTime() + (d * 24 * 60 * 60 * 1000);
	now.setTime(then);
	exp = '; expires=' + now.toGMTString();
	}
document.cookie = CookieName+'=set; path='+CookieDirectory+'; domain='+CookieDomain+exp;
}

function HasCookie() {
var cookiecontent = new String();
if(document.cookie.length > 0) {
	var cookiename = CookieName+'=';
	var cookiebegin = document.cookie.indexOf(cookiename);
	var cookieend = 0;
	if(cookiebegin > -1) {
		cookiebegin += cookiename.length;
		cookieend = document.cookie.indexOf(";",cookiebegin);
		if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
		cookiecontent = document.cookie.substring(cookiebegin,cookieend);
		}
	}
if(cookiecontent.length > 0) { return true; }
return false;
}
</script>

Instructions in the JavaScript tell you where (and what) to specify the domain name, the section of the website the cookie shall affect, how long the cookie shall persist, and the cookie's name.

Remove the <script...> and </script> tags if the JavaScript will be in a file separate from the web page

Will Bontrager

Was this blog post helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method


All information in WillMaster Blog articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

Recent Articles in the Library

Extracting Dates From the Unix Timestamp

The UNIX timestamp can be used to determine the represented time for any time zone on Earth.

Submit Form Data Without Bothering User

To silently and effectively submit a form on a web page, Ajax with FormData() can be used.

CSS Dots

CSS dots can be used for interactions between web page and website user.

Email Testing

One thing to test when email doesn't get sent or doesn't arrive is whether the server actuall sends email.

Tap to Select

Find out how to make a link or button to select the content in a div or other HTML element.

Capitalizing the First Letter of Words

Here, find both PHP code and JavaScript code to capitalize the first letter of a word.

Fixed-position Table Header

During a vertical scroll, the table header scrolls out of view -- unless the header is fixed in position.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC