Javascript variables after refresh page - javascript

I try to create my own collapsed sidebar, and I want to have the cookie saved for settings(collapsed or expanded bar). Here`s my code from to footer included file:
var cookieRightSideBar;
var $postscontainer;
var $container;
var $infocontainer;
cookieRightSideBar = document.cookie.replace(/(?:(?:^|.*;\s*)rightside_container\s*\=\s*([^;]*).*$)|^.*$/, "$1");
$postscontainer = document.getElementById('leftside');
$container = document.getElementById('rightside_container');
$infocontainer = document.getElementById('rightside');
function collapseRightside() {
document.cookie = (cookieRightSideBar == 'collapsed') ? 'rightside_container=expanded' : 'rightside_container=collapsed';
$postscontainer.style.width = ($postscontainer.style.width == '99%') ? '80%' : '99%';
$container.style.display = ($container.style.display == 'none') ? 'block' : 'none';
$infocontainer.style.width = ($infocontainer.style.width == '0%') ? '19%' : '0%';
}
if (document.getElementById('leftside')) {
var $myheight = document.getElementById ('leftside').offsetHeight - 62;
document.getElementById('rightside').style.maxHeight = $myheight + 'px';
}
if (cookieRightSideBar == 'expanded') {
$container.style.display = 'block';
$infocontainer.style.width = "19%";
$postscontainer.style.width = "80%";
}
Its almost worked, except couple sadly things.
Then after refresh a page, I click to button for expand my bar, looks like function collapseRightside not worked correctly after first click(bar collapsed if was expanded but not expanded if was collapsed). This function properly work with any stages only after second click.
And one more... If I collaps bar, and expand again and then refresh page, the bar appear collapsed.
I understarnd what I have mistakes in logical things, but I can`t understand where?
Thanks for any help!!!

This seems to fix your problem.
https://jsfiddle.net/L5unwnL9/5/
The problem was that you were checking for $container.style.display == 'none' while that value is null on page load. This fixed it on both container and infocontainer.
I've also added createCookie and getCookie functions just because it was easier to use for me.
var cookieRightSideBar;
var $postscontainer;
var $container;
var $infocontainer;
var e = document.getElementById('onclick');
e.onclick = collapseRightside;
cookieRightSideBar = getCookie("rightside_container")
$container = document.getElementById('rightside_container');
$infocontainer = document.getElementById('rightside');
function collapseRightside() {
cookieRightSideBar = (getCookie('rightside_container') == 'collapsed') ? 'expanded' : 'collapsed';
createCookie("rightside_container", cookieRightSideBar);
$container.style.display = (!$container.style.display || $container.style.display == 'none') ? 'block' : 'none';
$infocontainer.style.width = (!$infocontainer.style.width || $infocontainer.style.width == '0%') ? '19%' : '0%';
}
if (document.getElementById('leftside')) {
var $myheight = document.getElementById('leftside').offsetHeight - 62;
document.getElementById('rightside').style.maxHeight = $myheight + 'px';
}
if (cookieRightSideBar === 'expanded') {
$container.style.display = 'block';
$infocontainer.style.width = "19%";
}
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}

Related

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.

Input file upload multiple files not working on Mobile device

I have a generic file up loader which looks like this:
<span class="input-group-btn">
<span class="btn btn-default btn-fill btn-file">
Browse<input type="file" id="fileInputs" multiple accept="image/*" onclick="resetprogresss()">
</span>
</span>
I can upload multiple files with my Desktop no problems, but When I try and use the same functionality on a mobile device, I cannot seem to select multiple files.
here is the javascript:
var Filenames;
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
var MainPath = generateUUID();
var Names = [];
function UploadFiles() {
var SetDir = MainPath;
var fileInputs = document.getElementById("fileInputs");
if ('files' in fileInputs) {
if (fileInputs.files.length == 0) {
alert("Please select a file");
return;
} else {
var file = fileInputs.files[0];
var ar = $("#AutoResumeBoxs").is(":checked");
var chunksize = 20000;
var name = SetDir;
/*
Arguments:
username name used to create subfolders on the server.
files files object from the file input tag.
uploadStartFunction function that receives a file object just before uploading.
progressFunction function that accepts a percent-complete integer value.
doneFunction function called when file is uploaded.
errorFunction function called when an error occurs.
chunkSize size in bytes of each chunk uploaded.
autoResume bool to control auto resuming.
*/
CFUpload(name, fileInputs.files, uploadStarts, progresss, dones, errors, chunksize, ar);
}
}
}
function uploadStarts(thisfile) {
Names.push(thisfile.name);
}
function progresss(percent) {
var p = percent + "%";
$("#lblUPs").text(p);
$("#progressbars").width(p);
$("#progressbars").attr("data-appear-progress-animation", p);
$("#ProgressTabs").text(p);
}
function resetprogresss() {
progresss(0);
}
function dones() {
}
function errors(data) {
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
$(document).ready(function () {
$("#urls").hide();
document.getElementById("saveme").disabled = true;
var username = getCookie("username");
});
I use this library to upload the files. Any Advice would be greatly appreciated.
Well it depends on the selection method you choose on your mobile , however , my native Gallery , and file manager absloutely work fine on my mobile , just tap and hold the file you want to upload , and it will switch to multi selection mode :
Please note that there are many jQuery plugins out there to upload files like this one , so it is not necessary to use pure html input tag.

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

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.

How to change ID to Class in Javascript

What do you do to change a javascript from a ID to a Class? I tried to do it on my own but with no luck, this is what I ended up with. The original code was to show or hide an element and remember the users selection.
HTML:
<div class="popup" style="display:none">
<img src="image-url.jpg" alt="alt text" title="title text">
</div>
JAVASCRIPT:
function setCookie (name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie (name) {
var cookie = " " + document.cookie;
var search = " " + name + "=";
var setStr = null;
var offset = 0;
var end = 0;
if (cookie.length > 0) {
offset = cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = cookie.indexOf(";", offset);
if (end == -1) {
end = cookie.length;
}
setStr = unescape(cookie.substring(offset, end));
}
}
if (setStr == 'false') {
setStr = false;
}
if (setStr == 'true') {
setStr = true;
}
if (setStr == 'null') {
setStr = null;
}
return(setStr);
}
function hidePopup() {
setCookie('popup_state', false);
document.getElementsByClassName('popup').style.display = 'none';
}
function showPopup() {
setCookie('popup_state', null);
document.getElementsByClassName('popup').style.display = 'block';
}
function checkPopup() {
if (getCookie('popup_state') == null) {
// if popup was not closed
document.getElementsByClassName('popup').style.display = 'block';
}
}
document.getElementsByClassName gives you back a NodeList. And a NodeList doesn't have a style property that's useful...all it has is length, and indexes for each node in the list.
In order to set the style of every popup that was found, you should iterate through the NodeList. For example:
function showPopups() {
setCookie('popup_state', null);
var popups = document.getElementsByClassName('popup');
for (var i = popups.length - 1; i >= 0; --i) {
popups[i].style.display = '';
}
}
Of course, to hide them, you'd set the display to none instead.
If you know you'll only have one element to change, (1) why aren't you using an ID? :) but (2) you can just say document.getElementsByClassName('popup')[0] to access the one element. Note, though...if you ever have more than one, you'll only change the first one that way.

Categories