On this test site, I had a fancybox lightbox popping up fine. Then I added code in hopes to have it only popup on FIRST visit, but never again after. So I have some JS below that runs setCookie() when either link in the lightbox is clicked. And onload, I run checkCookie(). If the cookie exists, don't show the lightbox. If it doesn't exist, show the lightbox.
With my new setting, getting and checking code, I can't get the lightbox to work now, and I'm pretty sure it's because getCookie isn't properly "getting" the cookie. Does anyone see anything obviously wrong?
function setCookie() {
document.cookie="lightboxcookie=lightboxseen; expires=Thu, 18 Dec 2020 12:00:00 UTC";
}
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 "";
}
function checkCookie() {
var thecookie=getCookie("lightboxcookie");
if (thecookie != "") {
} else {
<!--Show Lightbox-->
jQuery.noConflict()(function ($) {
$(document).ready(function() {
$(".lightbox").fancybox();
$(".lightbox").eq(0).trigger('click');
$(".lightbox").fancybox({
helpers : {
overlay : {
css : {
opacity: 0.8,
'background-color' : '#ff0000'
}
}
}
});
});
});
}
}
}
</script>
It seems that you have one extra closing curly brace at the end of your checkCookie function. If you remove that your code appears to be working as expected: http://jsfiddle.net/akk6wx9q/
By the way, if you are going to handle cookies in the client side using JavaScript I suggest you take a look at the well tested and easy to use Cookie.js library. By using it you can save a lot of time and the pain of trying to develop cookie handling functions yourself ;)
Related
I am using a new setup for an eCommerce website that requires age verification popup. Usually i would rely on Jquery for that. However my new setup has its own complicated framework and I dont want to inject Jquery into the site just for this one popup. So i was wondering if it can also be done just using pure javascript?
Here is the Jquery version I am used to using: https://codepen.io/anon/pen/VgarjL
Here is the Jquery code from my pen above
$(document).ready(function(){
// put the popup at the start of the body
$('#ageWrapper').prependTo($('body'));
// check if the age has already been verified
if (($.cookie('age')) !== 'true') { $('#ageWrapper').addClass('ageConfirmed'); }
// if the "yes" button is clicked, add a cookie and hide the popup
$('#ageOkay').click(function() {
$.cookie('age', 'true', { expires: 1, path: '/' });
$('#ageWrapper').removeClass('ageUnknown');
});
// if the "no" button is clicked, take the user elsewhere
$('#ageBad').click(function() {
window.location.href='https://google.com';
});
});
There are many jquery versions/solutions online and even on stack overflow. However I am having trouble finding a Pure Javascript solution.
Thanks for any help
This is a way it could be solved. Take a careful look to understand what is happening:
/* Prepared function that will be checking if the Cookie exists (it will be called in the next function) */
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;
}
/* Conditional and function to check if Cookie doesn't exist. If so, it creates the Cookie */
if (getCookie('areYouOver18') !== 'yes') {
function createCookie(name,value,minutes) {
if (minutes) {
var date = new Date();
date.setTime(date.getTime()+(minutes*60*1000));
var expires = "; expires=" + date.toGMTString();
} else {
var expires = ""; // if time was not declared, the Cookie will expire next time browser closes
}
document.cookie = name+"="+value+";"+expires+"; path=/";
}
createCookie('areYouOver18', 'yes', (60*48));
// Cookie's name is "areYouOver18"
// Cookie's value is "yes"
// Cookie's expiry time is "48 hours"
yourFunction(); // The Cookie is created. Now this function can invoke modal
}
function yourFunction () {
// your function calling modal or doing something else
}
I am trying to execute a javascript alert, but only alert if it is the first time that browser / computer has viewed that page - or something similar to that.
How would this be done? I have written the Javascript to what I think it be similar to.
function alert() {
alert(" Please view this is Firefox");
}
if (first time viewing this page) {
alert();
}
I really appreciate your help
You could use the JQuery Cookie Plugin for this.
function showPopUp() {
var cookie = $.cookie('the_cookie');
if(!cookie){
alert(" Please view this in Firefox");
$.cookie('the_cookie', 'the_value');
}
}
showPopUp();
You can use localStorage or cookies:
Here is an example with localStorage:
var visited = localStorage.getItem('visited');
if (!visited) {
alert("Please view this is Firefox");
localStorage.setItem('visited', true);
}
Don't use a Cookie it will be sent to the server at each time your make request. You can use Local Storage instead, like:
function load() {
var isFired = localStorage.getItem('checkFired');
if (isFired != '1'){
alert(" Please view this is Firefox");
localStorage.setItem('checkFired', '1');
}
}
load();
See this link you will get some idea example is based on cookies...Once you typed you value and if you refresh it, it will show the value..
Set cookie
document.cookie="first=first";
Read a Cookie with JavaScript
var x = document.cookie;
Example:
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie()
{
var first=getCookie("first");
if(first == "first")
{
alert(" Please view this is Firefox");
}else{
document.cookie="first=first";
}
}
Cookie in JS
I have a Fancybox set on a delay to pop up on any page of my Wordpress, I'm looking to have it become disabled after a user submits something in the provided input or have it not show up for a given amount of time if the user clicks on the bypass link. I've tried a few scripts found around this site but nothing seemed to work, here's what I currently have set in place.
function openFancybox() {
setTimeout( function() {$('.pop').trigger('click'); },20000);
}
$(document).ready(function() {
var visited = $.cookie('visited');
if (visited == 'yes') {
return false;
} else {
openFancybox();
}
$.cookie('visited', 'yes', { expires: 7 });
$('.pop').fancybox();
});
Please try the below to see if that helps.
openFancybox = function{
setTimeout( function() {$('.pop').trigger('click'); },20000);
}
$(document).ready(function() {
//Declare your cookie.
$.cookie('visited','no', { expires: 7 });
//Test to see if your cookie equals 'no', if true then run the fancy box.
if ($.cookie('visited') == 'no') {
openFancybox();
}
//Your Input or click to stop the fancy box
$('#StopFancyBox').on('click',function(){
$.cookie('visited', 'yes');
});
});
As #Brad mentioned you can use the web developer tools to test to see what your cookie value is at stages. Simply go to the web.console and call back $.cookie('visited')
ERRORS
jquery.cookie.jsGET http://www.coreytegeler.com/bolivares/wp-content/themes/max-magazine/source/cookies/jquery.cookie.js 404 (Not Found)
The above seems to be because the jquery.cookie.js file is not referencing the right location.
/bolivares/:72SyntaxError: Expected token '('
The above is actually my fault :) sorry. When declaring the function openFancybox i missed off the (). So it should be openFancybox = function(){.
jquery-plugins.min.js:13TypeError: 'undefined' is not an object (evaluating 'e.browser.msie')
superfish.js:123TypeError: 'undefined' is not a function (evaluating 'jQuery('ul.nav').superfish()')
woocommerce.min.js:1TypeError: 'undefined' is not a function (evaluating 'e(".plus").live')
The above are conflicts with the plugins jquery-plugins.min.js, superfish.js and woocommerce.min.js respectively. I'm sorry I can't give much guidance on these.
/bolivares/:259ReferenceError: Can't find variable: myLoop
You're calling back myLoop(i) on line 259 on your main html page. But searching through all of your scripts, this isn't declared anywhere.
Yes you can edit it perfectly all you have to do is create a settimeout value so that the fancybox pops out after some time and then write the program like this
<script type="text/javascript">
function openFancybox() {
setTimeout( function() {$('#fancybox-manual-b').trigger('click'); },5000);
}
$(document).ready(function() {
var visited = $.cookie('visited');
$.cookie('visited', 'yes', { expires: 7 }); /*write this first*/
if (visited == 'yes') {
function callback(a){
return function(){
alert("Hello " + a);
}
}
var a = "world";
setTimeout(callback(a), 2000); /*let the page load first*/
a = "subscriber";
} else {
openFancybox();
}
$('#fancybox-manual-b').fancybox();
});
</script>
If you want you can change the (I wrote this to check if the cookie is working properly or not)
if (visited == 'yes') {
function callback(a){
return function(){
alert("Hello " + a);
}
}
var a = "world";
setTimeout(callback(a), 2000);
a = "idiotteen";
}
to
if (visited == 'yes') {
return false;
}
Let me know if this helped you
I've made a popup box for my site, which invites visitors to Like my page on FB. I wanted to know if there's a way to detect people who have liked the page, and remove the popup box (= a div), so it doesn't loads for them, everytime they browse back the site.
Don't know if this is possible, but I wanted to know. Here's the script I have for this, just in case you need it:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
var dom = {};
dom.query = jQuery.noConflict(true);
var time = 11;
window.setInterval(test, 1000);
function test()
{
time -=1;
dom.query('#fb-timer').html(time);
if(time == 0)
{
dom.query('#fb-popupdiv').remove();
}
}
function setCookie(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;
}
function eraseCookie(name) {
setCookie(name,"",-1);
}
dom.query(document).ready(function() {
var val = readCookie("popupAlreadyShown");
if (!val) {
setCookie("popupAlreadyShown", 1, 1);
dom.query("#fb-popupdiv").show();
} else {
}
});
</script>
Thanks in advance!
There's no way you can know from facebook's end that whether the page was liked or not unless you have access to user's likes. But for that you'll have to get the user signup via facebook connect.
Most of the like gates/popups use cookie to keep track of the like. When the user likes the page, facebooks's edge.create is used to listen to the like and a cookie is created. If the cookie is cleared the popup will appear again.
More about fb events:
https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
You want to take a look at the edge.Create event. Subscribe to it, and perform whatever functions you want within it. For example:
<script type='text/javascript'>
window.fbAsyncInit = function () {
FB.init({ appId: '1234567890', status: true, cookie: true,
xfbml: true
});
FB.Event.subscribe('edge.create', function (response) {
$("#facebookdiv").hide();
// set a variable or a cookie so it doesn't show on future requests
});
</script>
From the Facebook documentation on the page I linked:
edge.create - fired when the user likes something (fb:like). The response parameter to the callback function contains the URL that was liked:
"http://www.example.com/article1.php"
One of my friend climes that his Chrome browser tab sometimes changed into "tamll.com", which was the biggest shopping website in China.
At first I think it may be caused by a malware. But he has a clean os, and he checked everything in his computer.
Then I found this javascript. The code is always in the bottom of this question. And this script is being included in "bbs.gfan.com".
The script use window.opener.location to change another browser tab's webpage. When you open any pages in "bbs.gfan.com" from google.com(for example search "bbs.gfan.com" in google and click the first answer), this script check if the window.opener is not null, and set the window.opener.location to _5had0w.mall. Then the window.opener tab will be jumped to the new address.
Is there any way to block a script when it try to change window.opener.location? Or is there a way to directly disable the window.opener.location?
I think a normal webpage will never change this variable, it may only use by a ad script like this.
This kind of ad script made me feel sick. It is not only open a ad webpage but also another webpage will gone...
if ("undefined" == typeof (_5had0w)) {
_5had0w = [];
_5had0w.ssite = new RegExp("(www.baidu.com)|(www.google.c)|(www.youdao.com)|(search.cn.yahoo.com)|(search.yahoo.com)|(114search.118114.cn)|(bing.118114.cn)|(search.114.vnet.cn)|(bing.com)|(www.soso.com)|(www.sogou.com)|(www.taobao.com)|(gougou.com)|(www.gouwo.com)|(cache.baidu.com)|(m.baidu.com)|(baidu.asp)|(hao123.com)|(265.com)|(114la.com)|(115.com)|(etao.com)", "i");
_5had0w.win = window;
try {
if (parent && parent.f && parent.document.getElementById("fulliframe")) {
_5had0w.win = parent
}
} catch (e) {}
_5had0w.getcookie = function (sName) {
var aCookie = document.cookie.split("; ");
for (var i = 0; i < aCookie.length; i++) {
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0]) return unescape(aCrumb[1])
}
return ""
};
_5had0w.setcookie = function (sValue) {
date = new Date();
date.setMinutes(date.getMinutes() + 100);
document.cookie = "oc_busy=" + escape(sValue) + "; expires=" + date.toGMTString() + ";path=/"
};
_5had0w.mall = "http://gomallg.blogbus.com/?76";
_5had0w.np = false;
_5had0w.nvIt = function (lochref) {
try {
_5had0w.win.opener.location = lochref
} catch (e) {
try {
_5had0w.win.opener.navigate(lochref)
} catch (e2) {
try {
_5had0w.win.opener.opener.navigate(lochref)
} catch (e3) {
_5had0w.np = true
}
}
}
};
_5had0w.nvUrl = function () {
var _co = _5had0w.getcookie("oc_busy");
if (_co == "" || _co.indexOf("mall") < 0) {
_5had0w.nvIt(_5had0w.mall);
if (!_5had0w.np) {
_5had0w.setcookie(_co + "_mall")
}
}
};
_5had0w.oload = function () {
if (_5had0w.win.opener && "" == _5had0w.getcookie('rf6_auth')) {
if (_5had0w.ssite.test(_5had0w.win.document.referrer)) {
_5had0w.nvUrl()
}
}
};
try {
if (document.attachEvent) {
window.attachEvent("onload", _5had0w.oload)
} else {
window.addEventListener("load", _5had0w.oload, false)
}
} catch (e) {}
}
This web application is taking advantage of the fact that Google and other websites are being opened from gfan.com. Therefore, the gfan.com web application does have some control over the new windows, since it opened them.
If the script at the bottom of the application is what you suspect is causing the problem, you could try one of several adblockers you can get for Chrome and Firefox that are installable as extensions.
If that doesn't work, you could try to edit your host file and point the remote script's domain to 127.0.0.1 so you override the DNS locally. This assumes it is a remote script and not served from gfan.com itself; otherwise, you won't be able to access gfan.com either.
Chrome Adblock is an adblocker you can try.