Setting a cookie and then replacing a div with another div - javascript

I'm having an issue where i'm trying to use the jQuery plugin by Carhartl : https://github.com/carhartl/jquery-cookie
I thought this would a fairly easy thing to do, but i'm fairly new to jQuery and cookies especially and i'm really struggling now.
What I want to do is:
Set a cookie that registers the visit
Switch one div for another (in this case, change the sticky bar for a different sticky bar with different content)
Keep the new content in place for the returning visitor for x amount of time (if I can specify the exact time, the better)
Current code looks like this:
$(function() {
if(!$.cookie('repeatVisitor')) {
$.cookie("repeatVisitor", "true", { expires: 3 }); //expires in 3 days
setTimeout('showDivTwo();', 3000);
}
})
function showDivTwo() {
$('#sticky-bar').fadeOut();
$('#sticky-private').fadeIn();
}
I would really appreciate some help, i'm in desperate need!

Your cookie plugin usage looks correct; so does all of your code. I think it may be a logic issue.
Your code will never show the private div after the first time.
You can make this adjustment, but note that if you do, you will ALWAYS see the private div.
What seems to be missing is a specific action that the user needs to take to trigger the cookie, not just the cookie's lack of existence:
$(function() {
if(!$.cookie('repeatVisitor')) {
// if the user is not a repeat visitor, set the cookie
$.cookie("repeatVisitor", "true", { expires: 3 }); //expires in 3 days
}
if ($.cookie('repeatVisitor')) {
// if the cookie exists, show the custom div
setTimeout('showDivTwo();', 3000);
}
})
function showDivTwo() {
$('#sticky-bar').fadeOut();
$('#sticky-private').fadeIn();
}

Related

Toggling localStorage item

I want to create a toggle function for my localStorage as I am trying to install a dark mode on my site and I want it to remember the user's choice.
I want it load the current preference on page load, if one has been made, and then toggle the state on click. My code is below - however I am clearly making some error on my attempt to toggle the localStorage state.
// ON PAGE LOAD, IF USER PREFERS DARK, ADD DARK CLASS TO HTML
if (window.localStorage.getItem('preferDark')) {
$('html').toggleClass('dark');
}
// TOGGLE STATE ON CLICK
$('.wrapper').click(function(){
if (window.localStorage.getItem('preferDark', true)) {
window.localStorage.setItem('preferDark', false);
} else {
window.localStorage.setItem('preferDark', true);
}
$('html').toggleClass('dark');
});
I know there are various localStorage toggle questions out there but I can't find one quite the same as mine.
You can't keep boolean in localStorage. That's why you have an error.
Try to keep, for example, 0 for false and 1 for true. But remember that localStorage also can't keep integer - you can pass integer or boolean but it will be converted to string.
Try this:
if (+window.localStorage.getItem("preferDark")) {
$("html").toggleClass("dark");
}
$(".wrapper").click(function () {
if (+window.localStorage.getItem("preferDark")) {
window.localStorage.setItem("preferDark", 0);
} else {
window.localStorage.setItem("preferDark", 1);
}
$("html").toggleClass("dark");
});
Pay attention: I use + sign before getting value from localStorage to convert it to Number

Using FullCalendar, how to add information to EventObject when eventReceive?

I've started discovering and using FullCalendar but I'm stuck with it.
What I want to do is a ResourceTimeline in Month view, with external event dragging (a left panel).
The subject later would be to have a modal when you drop an event, in order to choose if you want the event to be from 8am to 12pm, or afternoon from 12pm to 6pm.
So first, I'd like to do a simple eventReceive without modal, to see if I can update the event when it's dropped.
But it seems I can't, what do I do wrong ?
From what I can understand, it looks like when you drop an event in month view, the event in the param sent to eventReceive is modified.
eventReceive(info) {
info.event.start = moment(info.event.start).add(8, 'hours').format('YYYY-MM-DD hh:mm:ss');
// var c = confirm('OK = morning, Cancel = aprem');
// if (c) {
// console.log("morning !")
// } else {
// console.log("afternoon !")
// }
}
Events are very basic because I wanted to complete them whenever I drop them into the calendar
new Draggable(listofEvents, {
itemSelector: '.draggable',
eventData(event) {
return {
title: event.innerText,
activite: event.dataset.activite,
allDayDefault: false,
}
},
})
I even tried to force allDayDefault to false but it doesn't change a thing...
Here is the codepen of the project in its current state : https://codepen.io/nurovek/pen/zYYWGyX?editors=1000
Sorry if my post lacks information, I'm not used to ask questions on SO. If it's lacking, I'll try to be more explicit if you ask me, of course !
As per the documentation, an event's public properties (such as "start", "end", title" etc) are read-only. Therefore to alter a property after the event is created you must run one of the "set" methods.
So your idea will work if you use the setDates method:
eventReceive(info) {
info.event.setDates(moment(info.event.start).add(8, 'hours').toDate(), info.event.end, { "allDay": false } )
console.log(info.event);
}
Demo: https://codepen.io/ADyson82/pen/dyymawy?editors=1000
P.S. You might notice I also made a few other little changes to your CodePen, mainly to correct all the links to CSS and JS files, since it was generating all sorts of console errors. These errors were because links were wrong or simply referred to something non-existent, and for some reason you were also using files from two different versions of fullCalendar (4.3.0 and 4.3.1), which is never a good idea if you want to ensure full compatibility.

Auto update timeAgo value from submitted date

EDIT: I think I should make things more obvious.
What I am trying to do is to make the function that displays the "time ago" from the submitted date of the post auto refresh every minute so that it stays relatively accurate even if the template is not re rendered.
I'd like to auto update my timeago value in my template but it is not working.
I've tried to set up my code with a reactive function, based on the answer to a similar question (https://stackoverflow.com/a/17933506)
Here's my code:
var timeAgoDep = new Deps.Dependency(); // !!!
var timeAgo;
var timeAgoInterval;
Template.postItem.created = function() {
function getTimeago() {
//var now = new Date();
timeAgo = moment(this.submitted).twitter();
timeAgoDep.changed(); // !!!
};
getTimeago(); /* Call it once so that we'll have an initial value */
timeAgoInterval = Meteor.setInterval(getTimeago, 5000);
};
Template.postItem.posted = function() {
timeAgoDep.depend(); // !!!
return timeAgo;
};
Template.postItem.destroyed = function() {
Meteor.clearInterval(timeAgoInterval);
};
I'm pretty sure that the problem comes from this.submitted because if I assign timeAgo = now for example, it will display the time and update like it's supposed to.
I also know that moment(this.submitted).twitter() works fine because when all I do is return it through a helper, it works.
A much better way to do this is to just embrace Meteor's reactivity and render time-dependent values reactively. In your case, the problem is that you are invalidating the dependency once every 5 seconds for each postItem rendered, which will quickly turn into a huge mess.
See https://github.com/mizzao/meteor-timesync for a package that provides reactive time variables on the client (and they are synced to server time too!) It's basically doing what you want, but in a cleaner way. (Disclaimer: I wrote this package.)
You can use moment in the same way to compute the actual string to display. For example, get rid of all the other stuff and just use
Template.postItem.posted = function() {
return moment(this.submitted).from(TimeSync.serverTime());
}
The moment().twitter() extension doesn't seem like a good choice because it only uses the current client time and doesn't allow you to pass in a specific (i.e. server-synced) time or reactive value.

Automatically update table

I have a PHP script render a beautiful series of div elements from MySQL info, now I want it to update dynamically and add new divs as new fields in MySQL are added.
window.setInterval(function() {
$.get('tableup.php', function(balance) {
$('.containerDiv').html(balance);
});
}, 60000*0.1);
First question is how do I add the divs to the top of the container div with a fade effect?
Second question is how do I know which divs to return in tableup.php? I already have the dates of every field saved, would passing them to the tableup, parsing them, then running a proper query on the database work? How do I save the date client side? The format is like this 2012-11-17 13:26:31
Question 1:
Use something like
$('.containerDiv').prepend(balance).fadeIn('slow');
Be sure to set the "incoming" div's as display: none in your css, so you don't see a flash.
Question 2:
Sure, save the date as timestamp or in your format in a variable and just pass it to the script
var time = '2012-11-17 13:26:31';
window.setInterval(function() {
$.get('tableup.php', { lastTime: time }, function(balance) {
$('.containerDiv').html(balance);
//update time, either from server script or by using the client side time
});
}, 60000*0.1);

How to avoid showing loading text in Ext.form.ComboBox?

I use Ext.form.ComboBox in very similar way as in this example:
http://extjs.com/deploy/dev/examples/form/forum-search.html
What annoys me is that when the ajax call is in progress it shows loading text and I cannot see any results from before.
Eg I input 'test' -> it shows result -> I add 'e' (search string is 'teste') -> result dissapear and loading text is shown, so for a second I cannot see any result and think about if it's not what I'm searching for...
How can I change this to simply not to say anything when 'loading'...
The solution is to override 'onBeforeLoad' method of Ext.form.ComboBox:
Ext.override(Ext.form.ComboBox,
{ onBeforeLoad:
function() {this.selectedIndex = -1;}
});
Please be warned, that this overrides the class method, so all of the ComboBox instances will not have the LoadingText showing. In case you would like to override only one instance - please use plugins (in quite similar way).
You may also look at Ext.LoadingMask to set an appropriate loading mask to aside element if you wish.
If you don't show loading message to user how user will know what is happening? User will notice that its already loading results so may wait to see the results, but if nothing displayed then user wouldn't know if its bringing new data or not.
You may monit the expand event of the combobox and set picker loading to false.
// in the controller
init: function() {
this.control({
"form combobox[id=fieldId]": {
expand: function(combobox) {
combobox.getPicker().setLoading(false);
}
}
});
}

Categories