Cookies to hide multiple elements - javascript

I am trying to hide random multiple elements, so what I have done was given each a unique ID.
$(function() {
var left= $('#left'),
right = $('#right'),
heads = $('.maintitle'),
i,
leftHead = $(left).find(heads),
rightHead = $(right).find(heads);
$(leftHead).prepend('<div class="close"></div>');
$(rightHead).prepend('<div class="close"></div>');
var close = $('.close'),
Lnumber = $('#left .module'),
Rnumber =$('#right .module');
for (i=0;i<Lnumber.length;i++) {
$(Lnumber)[i].id='widg'+i;
}
close.click(function() {
var id = $(this).parent().parent().attr('id');
$(this).parent().parent().slideUp().addClass('hidden');
SetCookie('hidden'+id,"true",100);
});
var cookieId = $('#left .module');
for (i=0;i<cookieId.length;i++) {
var newArray = [cookieId[i].id];
if (ReadCookie(newArray) == 'true') {
var cName = newArray.replace('hidden','');
alert(cName);
}
}
});
As you can see in the ReadCookie function I have it alerting the ID's that are hidden, though this doesn't work either yet. I am brand new to Cookies and just having a hard time getting this to work correctly.
Here are the functions for the cookies...
function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString(),';path = /';
}
function KillCookie(cookieName) {
SetCookie(cookieName,"", - 1);
}
function ReadCookie(cookieName) {
var theCookie=""+document.cookie;
var ind=theCookie.indexOf(cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
If anyone sees any other way to do this that is fine, just need to get the specific ID's to make sure they stay hidden when clicked and changing pages.

Have you tried the jQuery Cookie plugin?
https://github.com/carhartl/jquery-cookie
Then create expiring cookie, valid across entire site:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
Then to read the cookie:
$.cookie('the_cookie'); // => "the_value"

Related

Force Meteor To Refresh / Re-render Templates?

*For reference I'm using iron router.
Instead of a sign in page I have this global sign in form embedded in an nav (aka on every page).
Right now I'm doing a really hacky refresh to reload the page once a user logs in.
I would like to just reload to the template aka not refresh the whole page.
Basically just want the templates rendered function to rerun on login.
Here's my current login code:
'submit #login': function(event, template){
event.preventDefault();
var handle = template.find('#usernameLogin').value;
var secretKey = template.find('#passwordLogin').value;
Meteor.loginWithPassword(handle, secretKey, function(err){
if (err) {
alert(err);
}else{
$('#close').click();
/* replace this with reactive ajax or whatever when you can! */
Meteor._reload.reload();
}
});
},
My render function which I think may be the real issue now:
Template.tournament.rendered = function () {
thisCampaign = this.data;
var self = this;
if (this.data.tournament.live) {
/* if theres a registered user */
if (Meteor.userId()) {
/* Select a winner box */
var participants = $('.participant-id');
var currentParticipant;
var nextRound;
var thisMatch;
var nextMatch;
var bracket;
participants.map(function(index, value){
if ($(value).text() === Meteor.userId()) {
if ($(value).parent().find('.participant-status').text() === 'undetermined') {
nextRound = $(value).parent().find('.participant-round').text();
thisMatch = $(value).parent().find('.participant-match').text();
bracket = $(value).parent().parent().parent().find('.participant');
};
};
});
nextRound = parseInt(nextRound) + 1;
nextMatch = Math.round(parseInt(thisMatch)/2) - 1;
if (parseInt(thisMatch) % 2 != 0) {
currentParticipant = 0;
}else{
currentParticipant = 1;
}
var winnerOptions = '';
var winnerBox = $('<div class="select-winner">');
if (bracket) {
bracket.map(function(index, value) {
winnerOptions += '<span class="winner-option"> '+$(value).find('.participant-title').text()+' <div class="winner-info"> '+$(value).find('a').html()+' </div> </span>'
});
winnerBox.append(winnerOptions);
$($($('.round'+nextRound).find('li')[nextMatch]).find('.participant')[currentParticipant]).removeClass('loser').addClass('undetermined');
$($($('.round'+nextRound).find('li')[nextMatch]).find('.participant')[currentParticipant]).find('a').addClass('tooltip').html(winnerBox);
};
}else{
}
}else{
/* Tournament Start Time */
var tournamentStartTime = function(){
var d = new Date();
var n = d.getTime();
var currentTime = TimeSync.serverTime(n);
var startTime = self.data.card.startTime;
var difference = startTime - currentTime;
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var secondsDifference = Math.floor(difference/1000);
/* if ends (make tournament live server side?) */
if (hoursDifference < 0 || minutesDifference < 0 || secondsDifference < 0) {
Meteor.clearInterval(tStartTime);
Session.set("tournamentStartTime", false);
}else{
if (hoursDifference < 10) {hoursDifference = "0"+hoursDifference;}
if (minutesDifference < 10) {minutesDifference = "0"+minutesDifference;}
if (secondsDifference < 10) {secondsDifference = "0"+secondsDifference;}
var formattedTime = hoursDifference + ':' + minutesDifference + ':' + secondsDifference;
Session.set("tournamentStartTime", formattedTime);
}
};
Session.set("tournamentStartTime", '00:00:00');
tournamentStartTime();
var tStartTime = Meteor.setInterval(tournamentStartTime, 1000);
/* Allow new user sign up */
var alreadySignedUp = false;
var usersSignedUp = $('.participant-id')
usersSignedUp.map(function (index, user) {
if ($(user).text().trim() === Meteor.userId()) {
alreadySignedUp = true;
}
});
if (this.data.card.host != Meteor.user().username && !(alreadySignedUp)) {
var openSlots = [];
var allSlots = $('.participant');
allSlots.map(function (index, participant) {
if ($(participant).find('.participant-title').text().trim() === '' && !($(participant).hasClass('loser'))) {
openSlots.push(participant);
}
});
openSlots.map(function (openSlot, index) {
$(openSlot).removeClass('winner').addClass('undetermined');
});
}
/* if theres a registered user */
if (Meteor.userId()) {
}else{
}
}
};
From what i can see there, your rendered function would not work as you expect as the template may render while the loggingIn state is still occuring...
My suggestion would be to use something along the lines of {{#if currentUser}} page here{{/if}} and then put the code you are trying to run in the rendered in a helper inside that currentUser block that way it would only display and be called if there is a logged in user, otherwise it would not show up and you would not need to re-render the page to perform any of that.
Basically once the user has logged in, any helper (other than rendered) that has the Meteor.userId() or Meteor.user() functions being called would re-run automatically, otherwise you could perform login actions inside a Tracker.autorun function if they are global to your app per client.

Cookie Code not removing opened element of cookie

var openClose = $('.openClose');
openClose.on('click', function() {
var cook = ReadCookie('slideHide'),
miniParent = $(this).parent().parent().parent().children('.main-content'),
miniDisp = miniParent.css('display');
if (miniDisp ==="block") {
KillCookie('slideHide');
$(this).parent().parent().parent().children('.main-content').slideUp();
var slide = cook + "," + "#"+$(this)
.parent()
.parent()
.parent()
.parent().attr("id") +
" #"+$(this).parent()
.parent().parent().attr("id");
SetCookie('slideHide', slide, 100);
}
else
{
$(this).parent().parent().parent().children('.main-content').slideDown();
var newCookie=[];
var a= $('.module').children('.main-content').filter(":hidden");
for(var i=0;i<a.length;i++){
var d = $(a[i++]);
var c = "#"+d.parent('.module').attr('id');
}
newCookie= c;
console.log(newCookie);
KillCookie('slideHide');
SetCookie('slideHide',d, 100);
}
});
These are my cookie functions:
function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString(),';path = /';
}
function KillCookie(cookieName) {
SetCookie(cookieName,"", - 1);
}
function ReadCookie(cookieName) {
var theCookie=""+document.cookie;
var ind=theCookie.indexOf(cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
Setting the cookie to make it slideUp and stay hidden works, but when I try to open it, it slidesDown, then I refresh the page it doesn't stay open like it should.
To sort of get the picture - http://jsfiddle.net/zRT9u/
If you need to know more please ask me I am willing to provide more!
I edited the javascript it almost works but I am not getting all the objects that I need
NEW EDIT- Tried the $.map() function but when I open one, and refresh all of them are now open?
else {
$(this).parent().parent().parent().children('.main-content').slideDown();
KillCookie('slideHide');
var newCookie=[];
var a= $('.module').children('.main-content').filter(":hidden");
var c = $.map(a,function(n,i){
return $(n).parent().attr('id');
});
newCookie= c;
SetCookie('slideHide',newCookie, 100);
}
Fixed it by using $.map and .join()
var openClose = $('.openClose');
openClose.on('click', function() {
var cook = ReadCookie('slideHide'),
miniParent = $(this).parent().parent().parent().children('.main-content'),
miniDisp = miniParent.css('display');
if (miniDisp ==="block") {
KillCookie('slideHide');
$(this).parent().parent().parent().children('.main-content').slideUp();
var slide = cook+","+ "#"+$(this).parent().parent().parent().attr("id");
SetCookie('slideHide', slide, 100);
} else {
$(this).parent().parent().parent().children('.main-content').slideDown();
KillCookie('slideHide');
var newCookie=[],
a= $('.module').children('.main-content').filter(":hidden"),
c = $.map(a,function(n,i){
return "#"+$(n).parent().attr('id');
});
newCookie= c.join(',');
SetCookie('slideHide',newCookie, 100);
}
});
By creating a "global" array and then using the $.map function as well as adding "#"+ to the map function I was able to get the actual ID names. Then I set newCookie to c.join(',') and everything works perfectly after that!

Storing information in cookies

Does anyone know powerfull class for storing information in cookies?
I just want write something like:
var cookieStorage = new cookieStorage(100); // 100 - time to store data
var apple = {size:10, color:'red',weight:100};
cookieStorage.set('MyApple',apple);
var restoredApple = cookieStorage.get('MyApple');
My implementation(without time to storing)
var cookieStorage = {
set: function (key, value) {
$.cookie(key, $.toJSON(value));
},
get: function (key) {
var json = $.cookie(key);
return $.parseJSON(json);
}
}
Here is cookie plugin
You can use the JSON library to achieve this. You can download JSON here: https://github.com/douglascrockford/JSON-js
I created a simple example for you. If you want to make it short, you can use JQuery-cookie.
function setCookie(){
var current = new Array();
var user = new Object();
user.FirstName = "Robby";
user.LastName = "Shaw";
current.push(user); //The test value
var exdate=new Date();
exdate.setDate(exdate.getDate()+5); //Expire in 5 days
var cname = "test"; //cookie name
var value = JSON.stringify(current); //Parse the array
document.cookie=cname+ "=" +escape(value)+ ";expires="+exdate.toGMTString();
}
function getCookie(){
var current = new Array();
if (document.cookie.length>0){
c_start=document.cookie.indexOf("test=");
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
current = JSON.parse(unescape(document.cookie.substring(c_start,c_end)));
alert(current[0].FirstName+","+current[0].LastName);
}
}
}

simple code to Show / Hide with cookie

Does anyone know a code as simple as possible to show / hide HTML.
With:
-Store the cookies option
-Effect to the Show / Hide
The jquery cookie plugin could simplify cookie management. As far as showing/hiding HTML is concerned you may take a look at the show() and hide() methods.
It really depends on the event/reason the content needs to show/hide...
Is it user specific content that must appear for a particular user, if so, how are you identifying the user (sessions, openID)?
Or is it event driven, ie, a user clicks on a button and content shows/hides and the cookie stores the show/hide state?
Damo
Probably more than you need, but I use this with the tablesorter plugin to collapse/expand sections of tables, store the state in the cookie and with .toggle() you can get a nice effect.
function tableContainer(id,visible,sortColumn,sortOrder){
this.ID = id;
this.Visible = visible;
this.SortColumn = sortColumn;
this.SortOrder = sortOrder;
}
function bindTableHeaders(element){
//Bind click handler to the table THs to update object as to current sort column.
$("thead th","#" + element).bind("click",function(){
var order = this.order
var column = this.column
var $table = $(this).closest("table")
var visible = $table.attr("expanded") //Technically I suppose if you can click these then it must be visible
var id = $table.attr("id")
var tableObj = new tableContainer(id,visible,column,order);
$.cookie(element, JSON.stringify(tableObj), { secure: true }); //Write the current state into the section cookie
});
};
function recoverState(element) {
// pull cookie for page state and visibility
var elementData = $.cookie(element);
if (elementData != null){
// parse JSON based on object representation
var json = JSON.parse(elementData)
var id = json.ID;
var visible = json.Visible;
var sortColumn = json.SortColumn == undefined ? 0 : json.SortColumn
var sortOrder = json.SortOrder == undefined ? 0 : json.SortOrder
} else {
var id = element;
var visible = "true"
var sortColumn = 0;
var sortOrder = 0;
}
// switch visibility
if(visible == "false"){
toggleElement(element)
}
// Determine if this section has any data (eg. a <tbody>)
if ($("tbody","#" + id).length == 0 || $("tbody","#" + id).html() == "")
return
if (pageAction == "Edit"){
$("#" + id).tablesorter({widgets: ['zebra'], sortList: [[sortColumn,sortOrder]]});
} else {
$("#" + id)
.collapsible("td.collapsible",{
collapse:true
})
.tablesorter({widgets: ['zebra'], sortMultiSortKey:'false', sortList: [[sortColumn,sortOrder]]});
}
}
function toggleElement(element) {
if ($("#" + element).attr("expanded") == "true"){
$("#" + element).attr("expanded","false")
$("#" + element).hide();
var isVisible = "false"
} else {
$("#" + element).attr("expanded","true")
$("#" + element).show();
var isVisible = "true"
}
//Rewrite the cookie for this section changing only the visibility
var elementData = $.cookie(element);
var visible = isVisible;
if (elementData != null){
var json = JSON.parse(elementData)
var id = json.ID;
var sortColumn = json.SortColumn;
var sortOrder = json.SortOrder;
} else {
var id = element
var sortColumn = 0;
var sortOrder = 0;
}
var tableObj = new tableContainer(id,visible,sortColumn,sortOrder);
$.cookie(element, JSON.stringify(tableObj), { secure: true }); //Write the current state into the section cookie
}

How to find out user clicked 3 times through my website with Javascript

Is there any way in JavaScript how to find out user clicked through the same domain 2 or more times?
I need to popup a window after user clicked anywhere on the site for 3 times. I know how to do it after one click - with document.referrer or addEventListener, but then I'm lost.
I need something that will capture all click events (not only links) and count them.
Sure. You need to store a list of users' click events, either in a cookie, or in a server-side data store. On every recorded click, increment the count by one, and do your thing when the number hits 3.
Try using session cookies to store state between pages -- they're fast, pretty widely compatible, and will zero out when the browser shuts down, to keep from spamming your users' cookie jars.
I tried this and it worked fine:
window.onload = function() {
var clicked = readCookie('popunder');
if(clicked == null) {
clicked = 0;
}
var allLinks = document.getElementsByTagName("a");
for(i=0;i<=allLinks.length;i++) {
allLinks[i].addEventListener("click",countClicks,true);
}
function countClicks() {
if(clicked == 2) {
popunder(); //something to do
} else {
clicked++;
doCookie('popunder', clicked, 1);
alert(clicked);
}
}
function popunder() { alert('thats 3 clicks!'); }
function doCookie(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 readName = name + "=";
var cSplit = document.cookie.split(';');
for(var i=0;i < cSplit.length;i++) {
var sc = cSplit[i];
while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length);
if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length);
}
return null;
}
}
Thanks for all your advice.
I tried this code. But after the refresh the clicked variable goes to 0 again.
I need to save every new value of clicked into cookie (or whatever else), so its number will rise with every click on link on page.
Is it possible to change value of the variable in cookie this way?
window.onload = function(){
var **allLinks** = document.getElementsByTagName("a");
var **clicked** = 0;
**doCookie**('popunder',clicked,1);
for(i=0;i<=allLinks.length;i++){
allLinks[i].addEventListener("click",countClicks,true);
}
function **countClicks**(){
if(clicked == 3){
popunder(); //something to do
}
else{
alert(readCookie('popunder'));
return clicked++;
}
}
function **doCookie**(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 readName = name + "=";
var cSplit = document.cookie.split(';');
for(var i=0;i < cSplit.length;i++) {
var sc = cSplit[i];
while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length);
if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length);
}
return null;
}

Categories