Create and read cookie in drop down menu with javascript - javascript

I'm using this HTML code:
<head>
<link href="defualt.css" rel="stylesheet" type="text/css" />
<link href="theme1.css" title="theme1" rel="alternate stylesheet" type="text/css" />
<link href="theme2.css" title="theme2" rel="alternate stylesheet" type="text/css" />
<link href="theme3.css" title="theme3" rel="alternate stylesheet" type="text/css" />
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<form>
<select id="myList" >
<option value="default">Default</option>
<option value="theme1">Theme 1</option>
<option value="theme2">Theme 2</option>
<option value="theme3">Theme 3</option>
</select>
</form>
</body>
It's a form to change style sheets. This is the javascript I'm using:
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
createCookie("style", title, 7);
}
function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}
function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
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 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;
}
window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
function initate()
{
document.getElementById("myList").onchange = function() {
setActiveStyleSheet(this.value);
return false
};
}
window.onload = initate;
The changing of the style sheets work great but I want the option chosen in the menu to stay after I reload the page. This works as it should in Firefox but not in Chrome. I'm quite new to javascripts and I haven't written all of this code myself so I don't fully understand all of it. Is it possible to save the chosen option of the menu in the same cookie or is it better/easier to create a new one?

If you're reloading the page, there is nothing you can do to persist the state of the drop down selection within the page (HTML, Javascript) itself. I would suggest you use a cookie to store the current selection, read in the value on page load, and set the option in the drop down accordingly.
For cookie JS, see: http://www.quirksmode.org/js/cookies.html
function initate() {
window.selectBox = document.getElementById("myList");
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
getTheme();
selectBox.onchange = function () {
setActiveStyleSheet(this.value);
setTheme();
};
}
window.onload = initate;
function setActiveStyleSheet(title) {
var i, a, main;
for (i = 0; (a = document.getElementsByTagName("link")[i]) ; i++) {
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if (a.getAttribute("title") == title) a.disabled = false;
}
}
createCookie("style", title, 7);
}
function getActiveStyleSheet() {
var i, a;
for (i = 0; (a = document.getElementsByTagName("link")[i]) ; i++) {
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
}
function getPreferredStyleSheet() {
var i, a;
for (i = 0; (a = document.getElementsByTagName("link")[i]) ; i++) {
if (a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
}
function getTheme() {
var storedThemeVal = readCookie('selectedTheme');
if (storedThemeVal != null && storedThemeVal != "") {
for (var i = 0; i < selectBox.options.length; i++) {
if (selectBox.options[i].value == storedThemeVal) {
selectBox.selectedIndex = i;
}
}
}
}
function setTheme() {
var selectedThemeVal = selectBox.options[selectBox.selectedIndex].value;
createCookie('selectedTheme', selectedThemeVal);
}
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;
}
Note that Chrome does not support local cookies by default (file:// protocol). Either test this in a server environment, or enable file cookies by adding --enable-file-cookies to your shortcut to Chrome (so, if you have a shortcut, right click on it, click properties and edit the Target to include --enable-file-cookies at the very end, after the quotes).
Alternatively, you could also modify the URL (user a query string parameter) to store/read the current selection (similar to above). However, this of course would be lost if the user leaves the site and comes back to it.
Adding a parameter to the URL with JavaScript

Related

How do I run 1 of 3 javascript functions randomly?

I want to show a random image to a page visitor, then only show that same image to the same visitor until the cookie expires.
Everything works properly but I'm stuck on the initialization.
Basically, if there is no cookie set, I need to run 1 of 3 functions randomly.
How would I go about choosing the one of 3 functions at random and running it?
$(document).ready(function() {
var cookie = readCookie("boatColor");
if (!cookie) {
console.log('Run one of 3 Functions Randomly');
} else if (cookie == "boatRed") {
showRedBoat();
} else if (cookie == "boatWhite") {
showWhiteBoat();
} else if (cookie == "boatBlue") {
showBlueBoat();
}
});
function showRedBoat() {
var newSrc = "";
var myText = "";
newSrc = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/500458/copeland_boat_red.jpg";
myText = "<h3>You've got the Red Boat!</h3>";
theImage.src = newSrc;
theDesc.innerHTML = myText;
createCookie("boatColor", 'boatRed', 0.00034722222);
}
function showWhiteBoat() {
var newSrc = "";
var myText = "";
newSrc = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/500458/copeland_boat_white.jpg";
myText = "<h3>You've got the White Boat!</h3>";
theImage.src = newSrc;
theDesc.innerHTML = myText;
createCookie("boatColor", 'boatWhite', 0.00034722222);
}
function showBlueBoat() {
var newSrc = "";
var myText = "";
newSrc = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/500458/copeland_boat_blue.jpg";
myText = "<h3>You've got the Blue Boat!</h3>";
theImage.src = newSrc;
theDesc.innerHTML = myText;
createCookie("boatColor", 'boatBlue', 0.00034722222);
}
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 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;
}
Codepen Link: https://codepen.io/nolaandy/pen/awgoQM
You could use new Date().getTime() % 3 to get a pseudo random number between 0 and 2. Then just use a switch statement to call one function or another.
My solution is to generate a random number if there is no cookie set, then run one of three functions based on that number:
$(document).ready(function() {
var cookie = readCookie("boatColor");
if (!cookie) {
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var randomNumber = getRandomInt(0,2);
if (randomNumber == 0) {
showRedBoat();
} else if (randomNumber == 1) {
showWhiteBoat();
} else if (randomNumber == 2) {
showBlueBoat();
}
} else if (cookie == "boatRed") {
showRedBoat();
} else if (cookie == "boatWhite") {
showWhiteBoat();
} else if (cookie == "boatBlue") {
showBlueBoat();
}
});

How to use jQuery click not jumping to top of page

I'm using the following jQuery code for open my shop URL in a new tab windows when user click any part of page :
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value) {
var exdays = 1;
var exdate = new Date();
exdate.setHours(exdate.getHours() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function checkCookie() {
var username1 = getCookie("tabligh1");
var username2 = getCookie("tabligh2");
var usernam = "sendshod";
if (username1 == null | username2 == null) {
window.open('#', '_parent', 'toolbar=1,location=1,directories=1,status=1,menubar=1?,scrollbars=1,resizable=1');
window.focus();
}
if (username1 == "" | username1 == null) {
if (window.open('http://shop.url')) {
window.focus();
setCookie("tabligh1", usernam);
}
}
}
// document.onclick = checkCookie;
jQuery(document).click(function (event) {
if (!jQuery(event.target).is('.hamyar_area, .hamyar_area *')) {
checkCookie();
}
})
if ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined)) window.onload = checkCookie;
When user click in page , a # character add end of correct URL like this:
before click : domain.com
after click : domain.com/#
And when # character add to end of URL, page jumping to top of page.
I want to use this jquery code but I don't want when user click on the page, page don't jumping to the top.

Javascript Expandable Header not working correctly

I am using a piece of Javascript that enables the user to expand a h3 tag in my HTML document. It is working perfectly however when I refresh my page the first time the header is contracted and then when I refresh it a second time the header is expanded again.
I would like it to just stay expanded and not contract ever but I am unsure what changes I may need to make to the code:
I should point out that when the user visits the page for the first time the header is already expanded. I do that by calling the function from within the body tag.
<body onLoad="expandcontent('sc1')">
This is the code:
var enablepersist = "on" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious = "yes" //Collapse previously open content when opening present? (yes/no)
if (document.getElementById) {
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}
function getElementbyClass(classname) {
ccollect = new Array()
var inc = 0
var alltags = document.all ? document.all : document.getElementsByTagName("*")
for (i = 0; i < alltags.length; i++) {
if (alltags[i].className == classname)
ccollect[inc++] = alltags[i]
}
}
function contractcontent(omit) {
var inc = 0
while (ccollect[inc]) {
if (ccollect[inc].id != omit)
ccollect[inc].style.display = "none"
inc++
}
}
function expandcontent(cid) {
if (typeof ccollect != "undefined") {
if (collapseprevious == "yes")
contractcontent(cid)
document.getElementById(cid).style.display = (document.getElementById(cid).style.display != "block") ? "block" : "none"
}
}
function revivecontent() {
contractcontent("omitnothing")
selectedItem = getselectedItem()
selectedComponents = selectedItem.split("|")
for (i = 0; i < selectedComponents.length - 1; i++)
document.getElementById(selectedComponents[i]).style.display = "block"
}
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue = unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function getselectedItem() {
if (get_cookie(window.location.pathname) != "") {
selectedItem = get_cookie(window.location.pathname)
return selectedItem
} else
return ""
}
function saveswitchstate() {
var inc = 0,
selectedItem = ""
while (ccollect[inc]) {
if (ccollect[inc].style.display == "block")
selectedItem += ccollect[inc].id + "|"
inc++
}
document.cookie = window.location.pathname + "=" + selectedItem
}
function do_onload() {
uniqueidn = window.location.pathname + "firsttimeload"
getElementbyClass("switchcontent")
if (enablepersist == "on" && typeof ccollect != "undefined") {
document.cookie = (get_cookie(uniqueidn) == "") ? uniqueidn + "=1" : uniqueidn + "=0"
firsttimeload = (get_cookie(uniqueidn) == 1) ? 1 : 0 //check if this is 1st page load
if (!firsttimeload)
revivecontent()
}
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload = do_onload
if (enablepersist == "on" && document.getElementById)
window.onunload = saveswitchstate

Changing style sheets not working in IE

I've got a style sheet changer with javascript but it doesn't work in IE while working good in Firefox and Chrome. The HTML code I'm using is this:
<head>
<link href="defualt.css" rel="stylesheet" type="text/css" />
<link href="theme1.css" title="theme1" rel="alternate stylesheet" type="text/css" />
<link href="theme2.css" title="theme2" rel="alternate stylesheet" type="text/css" />
<link href="theme3.css" title="theme3" rel="alternate stylesheet" type="text/css" />
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<form>
<select id="myList" >
<option value="default">Default</option>
<option value="theme1">Theme 1</option>
<option value="theme2">Theme 2</option>
<option value="theme3">Theme 3</option>
</select>
</form>
</body>
And the javascript:
function setActiveStyleSheet(title) {
var i, a, main;
for (i = 0; (a = document.getElementsByTagName("link")[i]) ; i++) {
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if (a.getAttribute("title") == title) a.disabled = false;
}
}
createCookie("style", title, 7);
}
function getActiveStyleSheet() {
var i, a;
for (i = 0; (a = document.getElementsByTagName("link")[i]) ; i++) {
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
}
function getPreferredStyleSheet() {
var i, a;
for (i = 0; (a = document.getElementsByTagName("link")[i]) ; i++) {
if (a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
}
function getTheme() {
var storedThemeVal = readCookie('selectedTheme');
if (storedThemeVal != null && storedThemeVal != "") {
for (var i = 0; i < selectBox.options.length; i++) {
if (selectBox.options[i].value == storedThemeVal) {
selectBox.selectedIndex = i;
}
}
}
}
function setTheme() {
var selectedThemeVal = selectBox.options[selectBox.selectedIndex].value;
createCookie('selectedTheme', selectedThemeVal);
}
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;
}
function initiate()
{
window.selectBox = document.getElementById("myList");
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
getTheme();
selectBox.onchange = function () {
setActiveStyleSheet(this.value);
setTheme();
};
}
window.onload = initiate;
I can't understand why this won't work in IE since it's working so good in the other browsers. And I prefer to keep all my javascript in my separate document javascript.js as well as I don't want to work with a library.
i don't know whether there is any other wrong in your code.but i know getElementsByClassName() is not supported lt IE9,and in ie,to the event binding method is attachEvent().I hope it can help u.
Probably because IE has issues getting non-standard attributes from elements.
Also you might want to try the following instead of 'getElementsByClassName()' (not supported)
i = 0;
a = document.getElementsByTagName("a");
while (element = a[i++]) {
if (element.className == "sidemenu-maincat") {
// blah blah...
}
}

javascript form cookies - select only opening cookie for first 10 indexes

I have never used cookies before, so I am using a peice of code I am very unfamiliar with.
It was working all fine, until I noticed just now that for select boxes, it is not working for any values after the tenth index. (for index 10 and above).
I have looked at the cookie stored on my system, and it appears t be saving them correctly. (I saw select10) ETC stored properly.
When it runs onload of body however, it is not loading in the values properly.
Here is the cookie code I am using:
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var expDays = 100;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) { endstr = document.cookie.length; }
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
// use the following code to call it:
// <body onLoad="cookieForms('open', 'form_1', 'form_2', 'form_n')" onUnLoad="cookieForms('save', 'form_1', 'form_2', 'form_n')">
function cookieForms() {
var mode = cookieForms.arguments[0];
for(f=1; f<cookieForms.arguments.length; f++) {
formName = cookieForms.arguments[f];
if(mode == 'open') {
cookieValue = GetCookie('saved_'+formName);
if(cookieValue != null) {
var cookieArray = cookieValue.split('#cf#');
if(cookieArray.length == document[formName].elements.length) {
for(i=0; i<document[formName].elements.length; i++) {
if(cookieArray[i].substring(0,6) == 'select') { document[formName].elements[i].options.selectedIndex = cookieArray[i].substring(7, cookieArray[i].length-1); }
else if((cookieArray[i] == 'cbtrue') || (cookieArray[i] == 'rbtrue')) { document[formName].elements[i].checked = true; }
else if((cookieArray[i] == 'cbfalse') || (cookieArray[i] == 'rbfalse')) { document[formName].elements[i].checked = false; }
else { document[formName].elements[i].value = (cookieArray[i]) ? cookieArray[i] : ''; }
}
}
}
}
if(mode == 'save') {
cookieValue = '';
for(i=0; i<document[formName].elements.length; i++) {
fieldType = document[formName].elements[i].type;
if(fieldType == 'password') { passValue = ''; }
else if(fieldType == 'checkbox') { passValue = 'cb'+document[formName].elements[i].checked; }
else if(fieldType == 'radio') { passValue = 'rb'+document[formName].elements[i].checked; }
else if(fieldType == 'select-one') { passValue = 'select'+document[formName].elements[i].options.selectedIndex; }
else { passValue = document[formName].elements[i].value; }
cookieValue = cookieValue + passValue + '#cf#';
}
cookieValue = cookieValue.substring(0, cookieValue.length-4); // Remove last delimiter
SetCookie('saved_'+formName, cookieValue, exp);
}
}
}
// End -->
</script>
I beleive the problem lies with the following line, found about 3/4 of the way down the code block above (line 68):
if(cookieArray[i].substring(0,6) == 'select') { document[formName].elements[i].options.selectedIndex = cookieArray[i].substring(7, cookieArray[i].length-1); }
Just for reference, here is the opening body tag I am using:
<body style="text-align:center;" onload="cookieForms('open', 'ramsform', 'decksform', 'hullsform', 'crewform', 'shipwrightform'); Swap(crew0z,'crew0i'); Swap(crew1z,'crew1i'); Swap(crew2z,'crew2i'); Swap(crew3z,'crew3i'); Swap(crew4z,'crew4i'); Swap(crew5z,'crew5i'); Swap(crew6z,'crew6i'); Swap(crew7z,'crew7i'); Swap(crew8z,'crew8i'); Swap(crew9z,'crew9i');" onunload="cookieForms('save', 'ramsform', 'decksform', 'hullsform', 'crewform', 'shipwrightform');">
(Please ignore the swap()'s as they are unrelated)
Page I am working on can be found: http://webhostlet.com/POP.htm
In both the open and save codes, change:
document[formName].elements[i].options.selectedIndex
to:
document[formName].elements[i].selectedIndex
options is an array of all the options, the selectedIndex property belongs to the select element that contains them.
Change:
cookieArray[i].substring(7, cookieArray[i].length-1)
to:
cookieArray[i].substring(6)
You were off by 1 because you forgot that it's 0-based counting. The second argument isn't needed, it defaults to the rest of the string.
The reason it worked for the first 10 menu items is a quirk of substring: if the second argument is lower than the first, it swaps them! So "select5".substring(7, 6) is treated as "select5".substring(6, 7), which gets the last character of the string. But for the longer strings, it was `"select35".substring(7, 7), which is an empty string.

Categories