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
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
}
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 ;)
I'm trying to test my local storage so I've tried a few examples.
this example worked before but now its not. not sure what happened
https://stackoverflow.com/questions/30116818/how-to-use-local-storage-form-with-html-and-javascript?noredirect=1#comment48344527_30116818/
Now I am trying this code and nothing pops up on if else, it just says local storage is
function lsTest() {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
var elem = document.getElementById('status');
if (lsTest() === true) {
elem.innerHTML += 'available.';
} else {
elem.innerHTML += 'unavailable.';
}
html
<div id="status">Local Storage is </div>
full code
http://tny.cz/39896a73
You should open your page using a webserver and not your local file system. The browser saves the localstorage data based on the host(domain). This prevents cross site local storage access.
Try this, using a webserver as Nimrodx said.
window.onload = function(){
function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
console.log(e);
return false;
}
}
var elem = document.getElementById('status');
if(lsTest() === true){
elem.innerHTML += 'available.';
}
else{
elem.innerHTML += 'unavailable.';
}
};
There is no issue with your method, but I didn't see any call to this method.
To make it functional, you need to call it with some event. Like: button / anchor onlick, window load / ready as following:
Javascript:
window.onload = function(){lsTest();}
jQuery:
jQuery(document).ready(function(){
lsTest();
});
DEMO
However, if you just want to check the browser compatibility of localStorage / sessionStorage then if(typeof(Storage) !== undefined){} is quite useful.
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"
Hi im looking a way to bookmark a page with JavaScript so that when a user reopens a course it remembers the page he or she is on by sending it to SCORM/Moodle.
any ideas folks?
using scorm 1.2 and Moodle 1.9:)
Many Thanks
<!-- ================ -->
<!-- Bookmarking start -->
<!-- ================ -->
<script type="text/javascript" src="SCORM_API_wrapper.js"></script>
<script type="text/javascript">
//Using pipwerks namespace, SCORM 1.2
var success = pipwerks.SCORM.init();
if(success){
var status = pipwerks.SCORM.get("cmi.core.lesson_status");
if(status != "completed"){
success = pipwerks.SCORM.get("cmi.core.lesson_status", "completed");
if(success){
pipwerks.SCORM.quit();
}
}
}
function setbookMark() {
var setlessonLocation = scorm.set("cmi.core.lesson_location", "2");
}
function showbookMark() {
alert(scorm.get("cmi.core.lesson_location"));
}
window.onload = function (){
init();
setbookMark();
}
</script>
<!-- ================ -->
<!-- Bookmarking End -->
<!-- ================ -->
First index page that is loaded
<script type="text/javascript" src="SCORM_API_wrapper.js"></script>
<script type="text/javascript">
var scorm = pipwerks.SCORM;
function init(){
//Specify SCORM 1.2:
scorm.version = "1.2";
var callSucceeded = scorm.init();
}
function end(){
var callSucceeded = scorm.quit();
}
function bookMark() {
var lessonLocation = scorm.get("cmi.core.lesson_location");
if (lessonLocation == "1") {
window.location = "1.html";
}
else if(lessonLocation == "2") {
window.location = "2.html";
}
else if(lessonLocation == "3") {
window.location = "3.html";
}
else if(lessonLocation == "4") {
window.location = "4.html";
}
else if(lessonLocation == "5") {
window.location = "5.html";
}
else if(lessonLocation == "6") {
window.location = "6.html";
}
else if(lessonLocation == "") {
window.location = "1.html";
}
}
window.onload = function (){
init();
bookMark();
}
window.onunload = function (){
end();
}
</script>
Setting lesson_location is the equivalent of creating a browser cookie... you need to write JavaScript in your course that parses the saved string and makes use of it.
You need to change your code in a number of places -- the code you've provided is an example that sets your course to complete the instant it's initialized. It isn't really what you're looking for.
Here's a quick primer on starting the course and looking for a bookmark:
var bookmark, initialized, status;
var scorm = pipwerks.SCORM; //shortcut for easier typing
function jumpToPage(url){
//write some code that navigates to the specified url
//Save whatever URL was just used as the bookmark
//each time the function is invoked.
scorm.set("cmi.core.lesson_location", url);
}
function init(){
//the default URL in case no bookmark is found
//or when course is launched for first time
var url = "url_of_first_page.html";
initialized = scorm.init();
if(!initialized){ alert("Course failed to initialize"); return false; }
//Get the lesson status from the LMS
status = scorm.get("cmi.core.lesson_status");
if(status === "completed"){
//You're already done, get out of here
scorm.quit();
return; //exit init() function
} else if(status === "ab-initio"){
//this is the very first launch, no bookmark will be found in LMS
//do nothing
} else {
//Check for a bookmark
bookmark = scorm.get("cmi.core.lesson_location");
//If a bookmark is found, use its value as the target URL
if(bookmark){
url = bookmark;
}
}
jumpToPage(url);
}
window.onload = init;
You can use cmi.core.lesson_location to store the learners current location in the course. If you need to store more complex information like the learners current state in the course then use cmi.suspend_data. These are both read/write properties that you can read when the course first loads and connects to the LMS and then navigate to the appropriate location within the course.
Quick reference on the CMI properties can be found under the Data Model section: http://scorm.com/scorm-explained/technical-scorm/run-time/run-time-reference/