How to only show pop up on first page load - javascript

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);
}

Related

Is there any possibility to execute function only once?

I have this code in JavaScript which is hiding some content. I actually want to hide-the content, before button is clicked. I know that maybe I could have empty elements and fill them after I click that button, but this looks like easier way.
I want to execute this function from the time user enters the page by the time he click on some button - then never, even after refresh.
Is it possible somehow?
function hideTheTable(){
document.getElementsByTagName('table')[0].style.visibility = "hidden"
document.getElementsByTagName('table')[1].style.visibility = "hidden"
document.getElementsByTagName('button')[1].style.visibility = "hidden"
document.getElementById('info').style.visibility = "hidden"
}
hideTheTable();
You can use the localStorage to store whether or not the function has already been run.
function hideTheTable(){
if(!localStorage.getItem('hideTableFlag')){
localStorage.setItem('hideTableFlag', true);
console.log('function run')
}
}
yes you can, by adding a cookie that returns if user entered the page before:
// first lets create a helper function that lets us retreive a cookie
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 "";
}
// setting cookie
// if you need the function to load when the page loads
window.onload = (){
document.cookie = "enteredbefore=true; path=/";
};
// else if you need to call it when user clicks on button (define your button)
mybutton.onclick = (){
document.cookie = "enteredbefore=true; path=/";
};
// now we make if else statment
if(getCookie(enteredbefore) == ""){
// call your function
hideTheTable();
}

How to hide a DIV when reloading a page?

I have a loading overlay that shows some information and I have a button to refresh the page. But I want the loading overlay only to appear once, not every time the button is clicked. (F5 doesn't matter). I was thinking of something like this:
<button type="button" onclick="reload();">
function reload() {
if (window.location.reload()) {
document.getElementById('loading').style.display = 'none';
}
}
But it doesn't work... pls help
You can make use of client cookie, set a flag to client cookie if overlay already shown once, example code:
Vanilla JS Version
<script>
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 "";
}
if (getCookie('OVERLAY_ALREADY_SHOWN')) {
document.getElementById('loading').style.display = 'none';
}
else {
// ... some conditions ...
setCookie('OVERLAY_ALREADY_SHOWN', true, 14); // persist two weeks
}
</script>
jQuery Cookie Version
<script src="/path/to/jquery.cookie.js"></script>
<script>
if ($.cookie('OVERLAY_ALREADY_SHOWN')) {
document.getElementById('loading').style.display = 'none';
}
else {
// ... some conditions ...
$.cookie('OVERLAY_ALREADY_SHOWN', true, { expires: 14 }); // persist two weeks
}
</script>

(php - javascript) popup when opening website on mobile

How can I make popup ads work only one time for mobile ios browser.
I am using (popup show every time : how I can make it show only first time)
<script type="text/javascript">
if( /iPad|iPhone/i.test(navigator.userAgent) ) {
var url=confirm("Would you like to download our mobile application?");
if (url==true)
{
var url = window.location.href = 'http://itunes.apple.com/us/app/AppId';
url.show();
}
else
{
}
}
</script>
You should use cookies to store a value that the popup has been shown then add check to your popup that if the cookie exists then don't display the popup. I updated your code to reflect the changes you need to make, goodluck :)
<script type="text/javascript">
if( /iPad|iPhone/i.test(navigator.userAgent) ) {
//cookie name mypopup not found so display the popup
if(!getCookie("mypopup")){
setCookie("mypopup",true); //sets the cookie mypopup
var url=confirm("Would you like to download our mobile application?");
if (url==true)
{
var url = window.location.href = 'http://itunes.apple.com/us/app/AppId';
url.show();
}else{
}
}
}
//function to retrieve cookie value
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 to set the cookie
function setCookie(cname, cvalue) {
document.cookie = cname + "=" + cvalue + "; ";
}
</script>
You could load the js externally
<script src="ad.php"></script>
And let the php check if the user saw it allready:
AD.PHP:
<?php
session_start();
if(!isset($_SESSION["ad"])){
$_SESSION["ad"]="displayed";
?>
//your javascript goes here
<?php } ?>

Cookies in HTML page

So this code that i have works perfectly and exactly as i want it to. What is does is it takes the input "textmoney" and calculates how much money you make yearly. I have a link to another calculator that makes a more percise prediction. Basically i want to know how to have the website remember what the data input was on "textmoney" on the first page, so that when the user clicks on the more advanced calculator the website will remember the value of "textmoney" and the user won't have to type in the same data again. Do i use cookies?
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var $demo = $('#demo');
var $textMoney = $('#textmoney');
var $moneydiv = $('#moneydiv');
$('#advanced').hide();
function getmoney(){
var money = $textMoney.val();
if (isNaN(money) || money === '') {
$demo.text('You aint enter no $$$$$$');
} else {
var dailyE = $textMoney.val() * 365;
$demo.text('$' + dailyE + ' per day');
}
}
// on enter key
$textMoney.keydown(function(e) {
if (e.which === 13) {
getmoney();
$('#advanced').show();
} else if ($(this).val() === '') {
$demo.text('');
$('#advanced').hide();
}
}).mouseover(function() {
$(this).css('border', '1px solid black');
}).mouseout(function() {
$(this).css('border', '1px solid grey');
});
// on click
$moneydiv.click(function(){
getmoney();
$('#advanced').show();
});
});
</script>
You may use HTML5 Web Storate:
// Store
localStorage.setItem("textmoney", $textMoney.val());
// Retrieve
$textMoney.val(localStorage.getItem("textmoney"));
From W3Schools:
The data in localStorage will not be deleted when the browser is closed, and will be available the next day, week, or year.
If you want to store the value just while the browser (or tab) is open. You can use sessionStorage instead:
// Store
sessionStorage.setItem("textmoney", $textMoney.val());
// Retrieve
$textMoney.val(sessionStorage.getItem("textmoney"));
If your browser desn't support HTML5, cookies are also good idea but be aware that some browsers can also have blocked cookies.
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;
}
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 "";
}
// Store
setCookie("textmoney", $textMoney.val(), 999999 /* Expiration*/);
// Retrieve
$textMoney.val(getCookie("textmoney"));

Why does my cookie script not work?

I cant find out what is wrong with my cookie script on this site:
http://lampen.identitest.dk/
If you go to my site, you will find a hidden
<div id="popupDiv">
it does not show because of display: none in css but it should be showing and then if you click on a button it should be hiding in 24 hours.
this is my script:
$(document).ready(function() {
// If the 'hide cookie is not set we show the message
if (!readCookie('hide')) {
$('#popupDiv').show();
}
// Add the event that closes the popup and sets the cookie that tells us to
// not show it again until one day has passed.
$('#close').click(function() {
$('#popupDiv').hide();
createCookie('hide', true, 1)
return false;
});
});
// ---
// And some generic cookie logic
// ---
function createCookie(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) {
createCookie(name,"",-1);
}
I have found the cookie script on
http://jsfiddle.net/FcFW2/1/
and this is tested and works in a default html document with jQuery on.
I hope someone can help me out :)
Best regards Shane
There is a typo in your script tag declaration.
It should be <script type="text/javascript">
Currently it's <script type="type/javascript">
I don't see any errors in your code.

Categories