Adding Cookies to a simple function - javascript

I need to add cookies so that when one div is open (showing) and the user clicks refresh it remmber the the last state.
I know it should be easy but im a total noob at js script and have been scrathing more than my head over this one. Any help would be more than appreciated. I have looked though different examples on this forum but they are complectaed and not clear. Looking for a simple solution to a simple bit of code. Thank you!
<script type="text/JavaScript">
$(document).ready(function(){
$('a.row_view').click(function() {
$('.contentPadd.r_view').css('display', 'block');
$('.contentPadd.l_view').css('display', 'none')
$('.contentPadd.t_view').css('display', 'none');
});
$('a.list_view').click(function() {
$('.contentPadd.r_view').css('display', 'none') //horizontal
$('.contentPadd.l_view').css('display', 'block') //list
$('.contentPadd.t_view').css('display', 'none') //thumbnails
});
$('a.table_view').click(function() {
$('.contentPadd.r_view').css('display', 'none')
$('.contentPadd.l_view').css('display', 'none')
$('.contentPadd.t_view').css('display', 'block')
});
});
</script>
<a class="row_view">1</a> <a class="list_view">2</a> <a class="table_view">3</a>
<div class="contentPadd r_view">NUMBER 1</div>
<div class="contentPadd t_view">NUMBER 2</div>
<div class="contentPadd l_view">NUMBER 3</div>

I wrote a cookie handler that you can find here: http://forrst.com/posts/JavaScript_cookie_handler-JE9
To use it, create a new instance of the Ovenmitts object. Then, pass in two parameters to the bakeCookie method: name and value. Within your click function, do the following:
$('a.row_view').click(function() {
var cookieObj = new Ovenmitts();
cookieObj.bakeCookie('opened', 'a.row_view');
$('.contentPadd.r_view').css('display', 'block');
$('.contentPadd.l_view').css('display', 'none')
$('.contentPadd.t_view').css('display', 'none');
});
Then, on page load, call the admireCookie method:
$(document).ready(function() {
var cookieObj = new Ovenmitts();
var cookie = cookieObj.admireCookie('opened');
if (cookie === 'a.row_view') {
$('.contentPadd.r_view').css('display', 'block');
$('.contentPadd.l_view').css('display', 'none')
$('.contentPadd.t_view').css('display', 'none');
}
});
Let me know if you have any issues implementing this.
Also, instead of .css('display', 'block') and .css('display', 'none') you can use the jQuery .show() and .hide() functions.
You can overwrite the cookie by calling the bakeCookie method and passing in the same name (e.g. 'opened'). That way, you can pass in a value to it to remember which drawer is open.

Thanks to Nick.
create or add this to your .js file:
//cookie handler for listing layouts // to instantiate a new object,
create a variable and call the new operator // e.g. var myCookie = new
Ovenmitts(); // then you can access the methods of Ovenmitts through
myCookie.bakeCookie(), etc. var Ovenmitts = function() { var ctx =
this; // create a cookie // accepts 3 parameters: name, value,
days // cookie takes a key / value pair for name / value, expires /
days // days is optional, defaults to session end ctx.bakeCookie =
function(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 = ""; }
return document.cookie = name + "=" + value + expires + "; path=/"; }; // reads a cookie // accepts the name parameter (
first value in the cookie ) ctx.admireCookie = function(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i += 1 ) {
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; }; }; //end of cookie handler.
$(document).ready(function(){ //Product listing layout div switch
$('a.row_view').click(function() { var cookieObj = new
Ovenmitts();
cookieObj.bakeCookie('opened', 'a.row_view');
$('.contentPadd.r_view').show();
$('.contentPadd.l_view').hide();
$('.contentPadd.t_view').hide(); });
$('a.list_view').click(function() { var cookieObj = new
Ovenmitts();
cookieObj.bakeCookie('opened', 'a.list_view'); $('.contentPadd.r_view').hide();//horizontal
$('.contentPadd.l_view').show(); //list
$('.contentPadd.t_view').hide(); //thumbnails });
$('a.table_view').click(function() { var cookieObj = new
Ovenmitts();
cookieObj.bakeCookie('opened', 'a.table_view'); $('.contentPadd.r_view').hide(); $('.contentPadd.l_view').hide();
$('.contentPadd.t_view').show(); }); var cookieObj = new
Ovenmitts(); var cookie = cookieObj.admireCookie('opened'); if
(cookie === 'a.row_view') {
$('.contentPadd.r_view').show();
$('.contentPadd.l_view').hide();
$('.contentPadd.t_view').hide(); } var cookieObj = new Ovenmitts(); var cookie = cookieObj.admireCookie('opened'); if
(cookie === 'a.list_view') {
$('.contentPadd.r_view').hide();//horizontal
$('.contentPadd.l_view').show(); //list
$('.contentPadd.t_view').hide(); //thumbnails }
var cookieObj = new Ovenmitts(); var cookie = cookieObj.admireCookie('opened'); if (cookie === 'a.table_view') {
$('.contentPadd.r_view').hide(); $('.contentPadd.l_view').hide();
$('.contentPadd.t_view').show(); } //END Product listing layout
div switch
added this to my test.html page. Also add the js file:
<script language="javascript" src="YOURJSFILE.js"></script>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js.js"></script>
<a class="row_view">TEST 1</a>
<a class="list_view">TEST 2</a>
<a class="table_view">TEST 3</a>
added this to to my test.html page
<div class="contentPadd r_view">TEST 1</div>
<div class="contentPadd t_view">TEST 2</div>
<div class="contentPadd l_view">TEST 3</div>
THATS IT. - ADD TO PHP -ADD IMAGES - EXPAND - Etc.

Related

When the user closes the announcement don't show notification to user again

I have created a notification bar on my site that I don't want to be shown to users again on subsequent visits after they close it the first time. The bar works as expected, but I can't seem to get the cookie to work to not display it again
js
$(document).ready(function(){
$(".m-close").click(function(){
$(".m-bar").hide(600);
});
});
html code
<center>
<div class="m-bar m-red">
<a class="m-microphone"><i class="material-icons" style="font-size:26px;">mic</i></a>
<a class="m-content" style="color: white;">Something Text</a>
<a class="m-close" href="#"><i class="material-icons">close</i></a>
</div>
</center> <br><br>
Here is a code example:
function addCookie(name, value, days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(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;
}
// When clicking the close button
addCookie('hidden', 'yes', 30);
// Checks if the user chose to hide the announcement
const isHidden = getCookie('hidden');
if (isHidden == 'yes') {
// Hide the announcement
$(".m-bar").hide(600);
}
else {
// Show the announcement
// ...
}
First you can use the addCookie() function to add a cookie when you close the announcement.
After that when you display the announcement, check if the cookie hidden is set to yes, if it is set to yes then hide the announcement, otherwise show it.
Also of course you can use different names and values and expiration dates for your cookies, I recommend setting a long expiration date.
I donĀ“t choose use a Cookie for this, I will use the localStorage because is a simple notification:
$(window).on('load', function(){
//Create a variable for localStorage return
var confirm = {
notification: false
};
//Get the Data from localStorage
let dataconfirm = localStorage.getItem('confirm');
if(dataconfirm != null){
confirm.notification = dataconfirm;
}
console.log(confirm);
$(document).ready(function(){
$('form').on('click', function(e){
e.preventDefault();
if(!confirm.notification === true){
localStorage.setItem('confirm', true);
}
});
});
});

How to only show pop up on first page load

I am trying to only display a pop up on the first page load, but in my current script it only shows the pop up if you refresh the page. The popup should display the first time you come to the page but not again.
<script type="text/javascript">// <![CDATA[
document.addEventListener('DOMContentLoaded', function() {
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
$(document).ready(function() {
if(getCookie('popup') !== ''){
$('.popup-wrapper').css('display','block');
} else {
setCookie('popup','open',1);
}
$('.popup-close').click(function(){
setCookie('popup','close',1);
$('.popup-wrapper').css('display','none');
});
});
});
// ]]></script>
Any help would be greatly appreciated.
Is there a reason why you are using cookies?? If not you can use localStorage and write something a bit cleaner..
So for example
$(document).ready(function() {
// if localStorage doesnt have the shownPopUp item
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
}
$('.popup-close').click(function(){
// set the shownPopUp item in localStorage
localStorage.setItem('shownPopUp', true)
$('.popup-wrapper').css('display','none');
});
});
});
No need for the getCookie function
Cookies are more used for server-side functions, where localStorage is better for client-side functions. So what will happen here is your users will never see the popup again unless they delete there localStorage
Just add localStorage.setTtem after showing the popup. And don't forget to make the .popup-wrapper display:none
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
localStorage.setItem('shownPopUp', true);
}

set cookie and show div on first visit then hide

I am trying to set multiple cookies depending on if the div exists via javascript but I have ran into an issue that I cannot figure out. On first visit, I would like to show the div to the user if the div exists then set a cookie (called redCookie) that expires in 3 days. After cookie is set on page refresh div should not be present. After 3 days I would like the div to be shown again redDiv.show().
At the moment the div shows on all page refreshes. The cookie is set but unfortunately it shows every time. Something must be wrong with my if statement but not sure what.
if ((redCookie = true) && (redDiv.length > 0))
Here is a link to js fiddle: https://jsfiddle.net/9uh96bh7/
Here are my functions:
$( document ).ready(function() {
colourCookies();
});
function colourCookies () {
var redCookie = getCookie("red-cookie-name");
var redDiv = $('.red');
var yellowCookie = getCookie("yellow-cookie-name");
var yellowDiv = $('.yellow');
if ((redCookie = true) && (redDiv.length > 0)) {
redDiv.show();
setCookie("red-cookie-name", redCookie, 3);
console.log ('red cookie is set');
} else {
redDiv.hide();
}
if ((yellowCookie = true) && (yellowDiv.length > 0)) {
yellowDiv.show();
setCookie("yellow-cookie-name", yellowCookie, 3);
console.log ('yellow cookie is set');
} else {
yellowDiv.hide();
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
First, the code.
It should be if ((redCookie == true) && (redDiv.length > 0)) not if ((redCookie = true) && (redDiv.length > 0)).
= is assign, == means equal to.
Second, the logic part.
cookie isset -> hide div
cookie is not set -> show div, set cookie
(correct me if I miss understood.)
So the if statement should be:
if (redCookie == true){
//hide div
} else {
//show div
//set cookie
}
Third, you make a mistake when setting cookies.
you should set you cookie like setCookie("yellow-cookie-name", true, 3);
If you use setCookie("yellow-cookie-name", yellowCookie, 3); and yellowCookie is null, this will cause failure to your if statement.
I think problem is with setting cookie, as some of the browser like chrome not sets cookie when you are running it on local, if you host it on server or run it through visual studio, it will work.. Test once with hosting it in iis if possible, else you can use localStorage like below...
$( document ).ready(function() {
colourCookies();
});
function colourCookies () {
removeIfThreeDaysElapsed('red-ls');
removeIfThreeDaysElapsed('yellow-ls');
if (!localStorage.getItem('red-ls')) {
$(".red").show();
localStorage.setItem("red-ls", new Date().toGMTString());
} else {
$(".red").hide();
}
if (!localStorage.getItem('yellow-ls')) {
$(".yellow").show();
localStorage.setItem("yellow-ls", new Date().toGMTString());
} else {
$(".yellow").hide();
}
}
function removeIfThreeDaysElapsed(lsname){
var d1 = localStorage.getItem(lsname);
if(d1){
if(new Date() > new Date(new Date().getTime()+(3*24*60*60*1000))){
localStorage.removeItem(lsname);
}
}
}
You may need to edit the code to handle all the scenarios!
If you able to see the cookie in browser, then please try with check like below...
if (redCookie) {
redDiv.hide();
} else {
redDiv.show();
setCookie("red-cookie-name", true, 3);
}
Because when you are getting value back from cookie its datatype is not boolean, it gets converted to string, so either you check like above or can use redCookie === "true".
Hope this helps you.

Use javascript cookie to remember which div is shown

I've been trying to combine two javascript codes, one that makes other divs close when a new one is opened and one that uses cookies to remember whether a div was opened by a viewer.
As it is now it succeeds in remembering which div was open, but when I click to open the other div, it doesn't close the first div. If I click again to reopen the first div, it closes the second just like it's supposed to, and after that, if I click to open the second div it closes the first div like it's supposed to. And then it works perfectly fine after that. But I can't figure out why it won't close the first div on the initial click.
I'm very new to javascript, so I don't know much about how to manipulate it.
<body>
<script language="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 MyFunction2(divName){
setCookie('bookmark_state', false);
//hidden val
var hiddenVal = document.getElementById("tempDivName");
//hide old
if(hiddenVal.Value != undefined){
var oldDiv = document.getElementById(hiddenVal.Value);
oldDiv.style.display = 'none';
}
//show div
var tempDiv = document.getElementById(divName);
tempDiv.style.display = 'block';
//save div ID
hiddenVal.Value = document.getElementById(divName).getAttribute("id");
}
function MyFunction3(divName){
setCookie('bookmark_state', null);
//hidden val
var hiddenVal = document.getElementById("tempDivName");
//hide old
if(hiddenVal.Value != undefined){
var oldDiv = document.getElementById(hiddenVal.Value);
oldDiv.style.display = 'none';
}
//show div
var tempDiv = document.getElementById(divName);
tempDiv.style.display = 'block';
//save div ID
hiddenVal.Value = document.getElementById(divName).getAttribute("id");
}
function checkBookmark() {
if (getCookie('bookmark_state') == null) {
document.getElementById('bookmark').style.display = 'block';
}
if (getCookie('bookmark_state') == false) {
document.getElementById('bookmark2').style.display = 'block';
}
}
</script>
<input id="tempDivName" type="hidden"/>
<div id="bookmark" style="display:none"><a style="color:black" href="#" OnClick="MyFunction2('bookmark2'); return false;">*</a></div>
<div id="bookmark2" style="display:none"><a style="color:red" href="#" OnClick="MyFunction3('bookmark');">*</a></div>
<script>
checkBookmark();
</script>
</body>
Also, is there a way to use a single cookie to remember which of several divs is open (instead of just two divs)?
Yes, simply store the states of your open divs in an object and serialize it via JSON, e.g.
var states = {
"div1": true, // open
"div2": false // closed
}
setCookie("div_states", JSON.stringify(states));

javascript toggle to show/hide div

I have a javascript toggle function:
<script type="text/javascript">
function toggle(layer) {
var d = document.getElementById(layer);
d.style.display = (d.style.display == 'none') ? '' : 'none';
}
</script>
What this does is:
I have a few links on page and on click of these links it shows / hides the respective DIV section associated with it..
In the following two links it opens and closes div section named stusearch & facsearch
<a href="javascript:toggle('stusearch')" ><b>Student Manager</b></a>
<a href="javascript:toggle('facsearch')" ><b>Faculty Manager</b></a>
This works well except that, i would like to hide the previous shown toggle when a new toggle link is clicked, at the moment the previous one remains open, and the new one opens up below it.
I tweaked your code a bit here. I ended up adding a variable to store the divs you want to show/hide in case you want to add more divs to toggle:
var divs = [ "stusearch", "facsearch" ];
function toggle(layer) {
var d
for(var i = 0; i < divs.length; i += 1) {
d = document.getElementById(divs[i]);
d.style.display = 'none';
}
d = document.getElementById(layer);
d.style.display = '';
}
<script type="text/javascript">
function toggle(layer) {
var d = document.getElementById(layer);
d.style.visibility = (d.style.visibility == 'hidden') ? 'visible' : 'hidden';
}
</script>
In pure javascript, the easiest way is going to be to just 'remember' the last element you modified - aka:
var lastElement = null;
function toggle(elementId)
{
if(lastElement != null)
lastElement.style.display = 'none';
var newElement = document.getElementById(elementId);
newElement.style.display = (newElement.style.display == 'none') ? 'visible' : 'none';
if(newElement != lastElement)
lastElement = newElement;
}
You hide the last reference, then get the new one and show it.
You could keep a local var to it,
<script type="text/javascript">
function(){
var shown;
window.toggle = function(layer) {
if(shown)
shown.style.display = '';
var d = document.getElementById(layer);
d.style.display = (d.style.display == 'none') ? '' : 'none';
shown = d;
}
}
</script>
Alternatively, you could control the visibility with a css class and do a blanket removel of the class from all elements before setting it.
Here is a jQuery solution in case you ever decide to implement a library:
the JavaScript:
function toggle(layer) {
$('.toggleableSearch').hide();
$(layer).show();
}
the html:
<a href="javascript:toggle('stusearch')" ><b>Student Manager</b></a>
<a href="javascript:toggle('facsearch')" ><b>Faculty Manager</b></a>
<div id="stusearch" class="toggleableSearch"></div>
<div id="facsearch" class="toggleableSearch"></div>

Categories