Use cookies to hide popup - javascript

The following code opens a pop-up when the page loads (body onload). When a user has closed the pop-up, I don't want it to appear again. This can be done with cookies as far as I have understood, but how can it be added to this example?
<html>
<head>
<title>Popup</title>
<style type="text/css">
#blanket {
display:none;
background-color:#111;
opacity: 0.65;
*background:none;
position:absolute;
z-index: 9001;
top:0px;
left:0px;
width:100%;
}
#popUpDiv {
display:none;
position:fixed;
width:600px;
height:400px;
border:5px solid #000;
z-index: 9002;
padding: 16px;
border: 5px solid #50563C;
border-radius:15px;
background-color: #FFFFFF;
}
</style>
<script type="text/javascript">
function toggle(div_id) {
var el = document.getElementById(div_id);
if ( el.style.display == 'none' ) { el.style.display = 'block';}
else {el.style.display = 'none';}
}
function blanket_size(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportheight = window.innerHeight;
} else {
viewportheight = document.documentElement.clientHeight;
}
if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
blanket_height = viewportheight;
} else {
if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
blanket_height = document.body.parentNode.clientHeight;
} else {
blanket_height = document.body.parentNode.scrollHeight;
}
}
var blanket = document.getElementById('blanket');
blanket.style.height = blanket_height + 'px';
var popUpDiv = document.getElementById(popUpDivVar);
popUpDiv_height=blanket_height/2-200;//200 is half popups height
}
function window_pos(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerHeight;
} else {
viewportwidth = document.documentElement.clientHeight;
}
if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
window_width = viewportwidth;
} else {
if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
window_width = document.body.parentNode.clientWidth;
} else {
window_width = document.body.parentNode.scrollWidth;
}
}
var popUpDiv = document.getElementById(popUpDivVar);
window_width=window_width/2-300;//300 is half popups width
popUpDiv.style.left = window_width + 'px';
}
function popup(windowname) {
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
}
</script>
</head>
<body onload="popup('popUpDiv')">
<div id="blanket" style="display:none;"></div>
<div id="popUpDiv" style="display:none;">
<a href="#" onclick="popup('popUpDiv')" >Close</a>
</div>
Click to Open pop-up
</body>
</html>
Actually, I have a piece of code that works, but not along with the above JS and pop-up.
<script type="text/javascript">
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name) {
var cookie = " " + document.cookie;
var search = " " + name + "=";
var setStr = null;
var offset = 0;
var end = 0;
if (cookie.length > 0) {
offset = cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = cookie.indexOf(";", offset);
if (end == -1) {
end = cookie.length;
}
setStr = unescape(cookie.substring(offset, end));
}
}
if (setStr == 'false') {
setStr = false;
}
if (setStr == 'true') {
setStr = true;
}
if (setStr == 'null') {
setStr = null;
}
return (setStr);
}
function hidePopup() {
setCookie('popup_state', false);
document.getElementById('popUpDiv').style.display = 'none'; document.getElementById('blanket').style.display = 'none';
}
function showPopup() {
setCookie('popup_state', null);
document.getElementById('popUpDiv').style.display = 'block'; document.getElementById('blanket').style.display = 'block';
}
function checkPopup() {
if (getCookie('popup_state') == null) { // if popup was not closed
document.getElementById('popUpDiv').style.display = 'block'; document.getElementById('blanket').style.display = 'block';
}
}
</script>
I try to execute both scripts such as this:
<body onload="popup('popUpDiv');'checkPopup()';">
I have tried to merge the scripts, but I'm stuck.

Maybe try this:
function popup(windowname) {
if ($.cookie('the_popup') !== '1') {
$.cookie('the_popup', '1', {
expires: 365,
path: '/'
});
//Your code
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
}
}
This code show your popup only first time.
You need jQuery Cookie plugin

Related

Links doesn't work on mobile / touch devices

I use XSwitch.js at my project and everything is perfect in Desktop view. But when I try to open the link from mobile / touch device seems like nothing happens. It's at 100% not a problem of z-index and positioning. As you can see if you try to click on the Example link on any section you'll can't open the link from mobile. / touch. I tested the issue with iPhone X, Galaxy Tab and Chrome Dev tools. I broke my head of trying to solve this bug and would much appreciate any help. Thanks!
(function($) {
$.fn.XSwitch = function(options) {
return this.each(function() {
var _this = $(this),
instance = _this.data('XSwitch');
if (!instance) {
instance = new XSwitch(_this, options);
_this.data('XSwitch', instance);
}
if ($.type(options) === 'string') {
return instance[options]();
}
});
}
$.fn.XSwitch.defaults = {
selectors: {
sections: '.sections',
section: '.section',
page: '.pages',
active: '.active'
},
index: 0,
easing: 'ease',
duration: 500,
loop: true,
pagination: true,
keyboard: true,
direction: 'vertical',
callback: ''
}
var _prefix = (function(temp) {
var aPrefix = ['webkit', 'moz', 'o', 'ms'],
props = '';
for (var i = 0, len = aPrefix.length; i < len; i++) {
props = aPrefix[i] + 'Transition';
if (temp.style[props] !== undefined) {
return '-' + aPrefix[i].toLowerCase() + '-';
}
return false;
}
})(document.createElement('div'));
var XSwitch = (function() {
function XSwitch(element, options) {
this.settings = $.extend(true, $.fn.XSwitch.defaults, options);
this.element = element;
this.init();
}
XSwitch.prototype = {
init: function() {
var _this = this;
this.selectors = this.settings.selectors;
this.sections = this.element.find(this.selectors.sections);
this.section = this.sections.find(this.selectors.section);
this.direction = this.settings.direction === 'vertical' ? true : false;
this.pagesCount = this.pagesCount();
this.index = (this.settings.index >= 0 && this.settings.index < this.pagesCount) ? this.settings.index : 0;
this.canScroll = true;
if (!this.direction) {
_initLayout(_this);
}
if (this.settings.pagination) {
_initPaging(_this);
}
_initEvent(_this);
},
pagesCount: function() {
return this.section.size();
},
switchLength: function() {
return this.duration ? this.element.height() : this.element.width();
},
prve: function() {
var _this = this;
if (this.index > 0) {
this.index--;
} else if (this.settings.loop) {
this.index = this.pagesCount - 1;
}
_scrollPage(_this);
},
next: function() {
var _this = this;
if (this.index < this.pagesCount) {
this.index++;
} else if (this.settings.loop) {
this.index = 0;
}
_scrollPage(_this);
}
};
function _initLayout(_this) {
var width = (_this.pagesCount * 100) + '%',
cellWidth = (100 / _this.pagesCount).toFixed(2) + '%';
_this.sections.width(width);
_this.section.width(cellWidth).css('float', 'left');
}
function _initPaging(_this) {
var pagesClass = _this.selectors.page.substring(1),
pageHtml = '<ul class="' + pagesClass + '">';
_this.activeClass = _this.selectors.active.substring(1);
for (var i = 0, len = _this.pagesCount; i < len; i++) {
pageHtml += '<li></li>';
}
pageHtml += '</ul>';
_this.element.append(pageHtml);
var pages = _this.element.find(_this.selectors.page);
_this.pageItem = pages.find('li');
_this.pageItem.eq(_this.index).addClass(_this.activeClass);
if (_this.direction) {
pages.addClass('vertical');
} else {
pages.addClass('horizontal');
}
}
function _initEvent(_this) {
_this.element.on('click touchstart', _this.selectors.page + ' li', function() {
_this.index = $(this).index();
_scrollPage(_this);
});
_this.element.on('mousewheel DOMMouseScroll', function(e) {
if (!_this.canScroll) {
return;
}
var delta = -e.originalEvent.detail || -e.originalEvent.deltaY || e.originalEvent.wheelDelta;
if (delta > 0 && (_this.index && !_this.settings.loop || _this.settings.loop)) {
_this.prve();
} else if (delta < 0 && (_this.index < (_this.pagesCount - 1) && !_this.settings.loop || _this.settings.loop)) {
_this.next();
}
});
_this.element.on('touchstart', function(e) {
var startX = e.originalEvent.changedTouches[0].pageX,
startY = e.originalEvent.changedTouches[0].pageY;
_this.element.one('touchend', function(e) {
if (!_this.canScroll) {
return;
}
var endX = e.originalEvent.changedTouches[0].pageX,
endY = e.originalEvent.changedTouches[0].pageY,
changeY = endY - startY;
if (changeY > 50) {
_this.prve();
} else if (changeY < -50) {
_this.next();
}
});
e.preventDefault();
});
if (_this.settings.keyboard) {
$(window).on('keydown', function(e) {
var keyCode = e.keyCode;
if (keyCode === 37 || keyCode === 38) {
_this.prve();
} else if (keyCode === 39 || keyCode === 40) {
_this.next();
}
});
}
$(window).resize(function() {
var currentLength = _this.switchLength(),
offset = _this.settings.direction ? _this.section.eq(_this.index).offset().top : _this.section.eq(_this.index).offset().left;
if (Math.abs(offset) > currentLength / 2 && _this.index < (_this.pagesCount - 1)) {
_this.index++;
}
if (_this.index) {
_scrollPage(_this);
}
});
_this.sections.on('transitionend webkitTransitionEnd oTransitionEnd otransitionend', function() {
_this.canScroll = true;
if (_this.settings.callback && type(_this.settings.callback) === 'function') {
_this.settings.callback();
}
});
}
function _scrollPage(_this) {
var dest = _this.section.eq(_this.index).position();
if (!dest) {
return;
}
_this.canScroll = false;
if (_prefix) {
_this.sections.css(_prefix + 'transition', 'all ' + _this.settings.duration + 'ms ' + _this.settings.easing);
var translate = _this.direction ? 'translateY(-' + dest.top + 'px)' : 'translateX(-' + dest.left + 'px)';
_this.sections.css(_prefix + 'transform', translate);
} else {
var animateCss = _this.direction ? {
top: -dest.top
} : {
left: -dest.left
};
_this.sections.animate(animateCss, _this.settings.duration, function() {
_this.canScroll = true;
if (_this.settings.callback && type(_this.settings.callback) === 'function') {
_this.settings.callback();
}
});
}
if (_this.settings.pagination) {
_this.pageItem.eq(_this.index).addClass(_this.activeClass).siblings('li').removeClass(_this.activeClass);
}
}
return XSwitch;
})();
})(jQuery);
$(function() {
$('[data-XSwitch]').XSwitch();
})
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
overflow: hidden;
}
#container,
.sections,
.section {
position: relative;
height: 100%;
}
.section {
background-color: #000;
background-size: cover;
background-position: 50% 50%;
}
#section0 {
background-color: grey;
}
#section1 {
background-color: red;
}
#section2 {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<div id="container" data-XSwitch>
<div class="sections">
<div class="section" id="section0">
Example Link
</div>
<div class="section" id="section1">
Example Link
</div>
<div class="section" id="section2">
Example Link
</div>
<div class="section" id="section3">
Example Link
</div>
</div>
</div>
So I've found an issue - just commented this code:
_this.element.on('touchstart', function (e) {
var startX = e.originalEvent.changedTouches[0].pageX,
startY = e.originalEvent.changedTouches[0].pageY;
_this.element.one('touchend', function (e) {
if (!_this.canScroll) {
return;
}
var endX = e.originalEvent.changedTouches[0].pageX,
endY = e.originalEvent.changedTouches[0].pageY,
changeY = endY - startY;
if (changeY > 50) {
_this.prve();
} else if (changeY < -50) {
_this.next();
}
});
/* e.preventDefault(); */
});

Select box options not showing on iphone

I have a strange problem where the select box options are not showing up on iPhones. When you click the select box the screen flickers but does not show any options. Any ideas ?
You can see it in action here : http://demo.elusivethemes.com/affliction/product/blue-fire-shirt/
Ive figured out its the stickysidebar thats causing the issue. Is there anyway to modify this so it only runs on screensizes over a certain width ?
// Sticky Sidebar
(function() {
var $, win;
$ = this.jQuery || window.jQuery;
win = $(window);
$.fn.stick_in_parent = function(opts) {
var doc, elm, enable_bottoming, fn, i, inner_scrolling, len, manual_spacer, offset_top, parent_selector, recalc_every, sticky_class;
if (opts == null) {
opts = {};
}
sticky_class = opts.sticky_class, inner_scrolling = opts.inner_scrolling, recalc_every = opts.recalc_every, parent_selector = opts.parent, offset_top = opts.offset_top, manual_spacer = opts.spacer, enable_bottoming = opts.bottoming;
if (offset_top == null) {
offset_top = 0;
}
if (parent_selector == null) {
parent_selector = void 0;
}
if (inner_scrolling == null) {
inner_scrolling = true;
}
if (sticky_class == null) {
sticky_class = "is_stuck";
}
doc = $(document);
if (enable_bottoming == null) {
enable_bottoming = true;
}
fn = function(elm, padding_bottom, parent_top, parent_height, top, height, el_float, detached) {
var bottomed, detach, fixed, last_pos, last_scroll_height, offset, parent, recalc, recalc_and_tick, recalc_counter, spacer, tick;
if (elm.data("sticky_kit")) {
return;
}
elm.data("sticky_kit", true);
last_scroll_height = doc.height();
parent = elm.parent();
if (parent_selector != null) {
parent = parent.closest(parent_selector);
}
if (!parent.length) {
throw "failed to find stick parent";
}
fixed = false;
bottomed = false;
spacer = manual_spacer != null ? manual_spacer && elm.closest(manual_spacer) : $("<div />");
if (spacer) {
spacer.css('position', elm.css('position'));
}
recalc = function() {
var border_top, padding_top, restore;
if (detached) {
return;
}
last_scroll_height = doc.height();
border_top = parseInt(parent.css("border-top-width"), 10);
padding_top = parseInt(parent.css("padding-top"), 10);
padding_bottom = parseInt(parent.css("padding-bottom"), 10);
parent_top = parent.offset().top + border_top + padding_top;
parent_height = parent.height();
if (fixed) {
fixed = false;
bottomed = false;
if (manual_spacer == null) {
elm.insertAfter(spacer);
spacer.detach();
}
elm.css({
position: "",
top: "",
width: "",
bottom: ""
}).removeClass(sticky_class);
restore = true;
}
top = elm.offset().top - (parseInt(elm.css("margin-top"), 10) || 0) - offset_top;
height = elm.outerHeight(true);
el_float = elm.css("float");
if (spacer) {
spacer.css({
width: elm.outerWidth(true),
height: height,
display: elm.css("display"),
"vertical-align": elm.css("vertical-align"),
"float": el_float
});
}
if (restore) {
return tick();
}
};
recalc();
if (height === parent_height) {
return;
}
last_pos = void 0;
offset = offset_top;
recalc_counter = recalc_every;
tick = function() {
var css, delta, recalced, scroll, will_bottom, win_height;
if (detached) {
return;
}
recalced = false;
if (recalc_counter != null) {
recalc_counter -= 1;
if (recalc_counter <= 0) {
recalc_counter = recalc_every;
recalc();
recalced = true;
}
}
if (!recalced && doc.height() !== last_scroll_height) {
recalc();
recalced = true;
}
scroll = win.scrollTop();
if (last_pos != null) {
delta = scroll - last_pos;
}
last_pos = scroll;
if (fixed) {
if (enable_bottoming) {
will_bottom = scroll + height + offset > parent_height + parent_top;
if (bottomed && !will_bottom) {
bottomed = false;
elm.css({
position: "fixed",
bottom: "",
top: offset
}).trigger("sticky_kit:unbottom");
}
}
if (scroll < top) {
fixed = false;
offset = offset_top;
if (manual_spacer == null) {
if (el_float === "left" || el_float === "right") {
elm.insertAfter(spacer);
}
spacer.detach();
}
css = {
position: "",
width: "",
top: ""
};
elm.css(css).removeClass(sticky_class).trigger("sticky_kit:unstick");
}
if (inner_scrolling) {
win_height = win.height();
if (height + offset_top > win_height) {
if (!bottomed) {
offset -= delta;
offset = Math.max(win_height - height, offset);
offset = Math.min(offset_top, offset);
if (fixed) {
elm.css({
top: offset + "px"
});
}
}
}
}
} else {
if (scroll > top) {
fixed = true;
css = {
position: "fixed",
top: offset
};
css.width = elm.css("box-sizing") === "border-box" ? elm.outerWidth() + "px" : elm.width() + "px";
elm.css(css).addClass(sticky_class);
if (manual_spacer == null) {
elm.after(spacer);
if (el_float === "left" || el_float === "right") {
spacer.append(elm);
}
}
elm.trigger("sticky_kit:stick");
}
}
if (fixed && enable_bottoming) {
if (will_bottom == null) {
will_bottom = scroll + height + offset > parent_height + parent_top;
}
if (!bottomed && will_bottom) {
bottomed = true;
if (parent.css("position") === "static") {
parent.css({
position: "relative"
});
}
return elm.css({
position: "absolute",
bottom: padding_bottom,
top: "auto"
}).trigger("sticky_kit:bottom");
}
}
};
recalc_and_tick = function() {
recalc();
return tick();
};
detach = function() {
detached = true;
win.off("touchmove", tick);
win.off("scroll", tick);
win.off("resize", recalc_and_tick);
$(document.body).off("sticky_kit:recalc", recalc_and_tick);
elm.off("sticky_kit:detach", detach);
elm.removeData("sticky_kit");
elm.css({
position: "",
bottom: "",
top: "",
width: ""
});
parent.position("position", "");
if (fixed) {
if (manual_spacer == null) {
if (el_float === "left" || el_float === "right") {
elm.insertAfter(spacer);
}
spacer.remove();
}
return elm.removeClass(sticky_class);
}
};
win.on("touchmove", tick);
win.on("scroll", tick);
win.on("resize", recalc_and_tick);
$(document.body).on("sticky_kit:recalc", recalc_and_tick);
elm.on("sticky_kit:detach", detach);
return setTimeout(tick, 0);
};
for (i = 0, len = this.length; i < len; i++) {
elm = this[i];
fn($(elm));
}
return this;
};
}).call(this);
Many thanks,
Scott

How to change the size of an iframe when device rotates?

I have a iframe with the id "myframe" I want to change the height when the device rotates. this works like this
<script>
$(document).on("pagecreate",function(event){
$(window).on("orientationchange",function(){
if(window.orientation == 0)
{
document.getElementById("myframe").height = 300;
}
else
{
document.getElementById("myframe").height = 500;
}
});
});
</script>
but needs to work like this
<script>
$(document).on("pagecreate",function(event){
$(window).on("orientationchange",function(){
if(window.orientation == 0)
{
var oldh = document.getElementById("myframe").height;
var newh = parseInt(oldh) * 1.4;
if(newh != ''){
document.getElementById("myframe").height = newh;
}
}
else
{
var oldh = document.getElementById("myframe").height;
var newh = parseInt(oldh) / 1.4;
if(newh != ''){
document.getElementById("myframe").height = newh;
}
}
});
});
</script>
if i print the results for var newh it returns correctly but still will not run my function
Your calculation might well result in a float number. You have to do it like this:
var newh = parseInt(oldh / 1.4);

Making my javaScript popup to appear only once

I am creating a JavaScript popup. The code is as below.
The HTML:
<div id="ac-wrapper" style='display:none' onClick="hideNow(event)">
<div id="popup">
<center>
<h2>Popup Content Here</h2>
<input type="submit" name="submit" value="Submit" onClick="PopUp('hide')" />
</center>
</div>
</div>
The CSS:
#ac-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: url("images/pop-bg.png") repeat top left transparent;
z-index: 1001;
}
#popup {
background: none repeat scroll 0 0 #FFFFFF;
border-radius: 18px;
-moz-border-radius: 18px;
-webkit-border-radius: 18px;
height: 361px;
margin: 5% auto;
position: relative;
width: 597px;
}
The Script:
function PopUp(hideOrshow) {
if (hideOrshow == 'hide') document.getElementById('ac-wrapper').style.display = "none";
else document.getElementById('ac-wrapper').removeAttribute('style');
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 0);
}
function hideNow(e) {
if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}
The jsFiddle Link:
http://jsfiddle.net/K9qL4/2/
The Issue:
The above script works fine, but I need to make the popUp to appear only once on my page.
i.e, when the user closes the popup, it should not appear until the user restarts the browser or clears his cache/cookie.
I tried using the below cookie script, but it does not work for me.
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var expDays = 1; // number of days the cookie should last
var page = "myPage.html";
var windowprops = "width=300,height=200,location=no,toolbar=no,menubar=no,scrollbars=no,resizable=yes";
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function amt(){
var count = GetCookie('count')
if(count == null) {
SetCookie('count','1')
return 1
}
else {
var newcount = parseInt(count) + 1;
DeleteCookie('count')
SetCookie('count',newcount,exp)
return count
}
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function checkCount() {
var count = GetCookie('count');
if (count == null) {
count=1;
SetCookie('count', count, exp);
window.open(page, "", windowprops);
}
else {
count++;
SetCookie('count', count, exp);
}
}
// End -->
</script>
I thing in this case is better to use localStorage instead cookie.
localStorage have a more intuitive interface and user cannot restrict
this feature to be used. I have changed your code.
function PopUp(hideOrshow) {
if (hideOrshow == 'hide') {
document.getElementById('ac-wrapper').style.display = "none";
}
else if(localStorage.getItem("popupWasShown") == null) {
localStorage.setItem("popupWasShown",1);
document.getElementById('ac-wrapper').removeAttribute('style');
}
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 0);
}
function hideNow(e) {
if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}
Here is working jsFiddle.
http://jsfiddle.net/zono/vHG7j/
Best regards.
To not show this untill restart browser - use local storage
localStorage.setItem("setted",true);
localStorage.getItem("setted");
FIDDLE
To not show untill clear cache\cookie use cookies
document.cookie = "setted=true";
document.cookie.indexOf("setted=true")!=-1
FIDDLE
I've used local storage instead of cookie for the reason mentioned otherwise
however, I have added the comparison, and checked that you want to show it (also added a reset button for you to test easily)
fiddle is: http://jsfiddle.net/K9qL4/8/
function PopUp(hideOrshow) {
if (hideOrshow === 'hide') {
document.getElementById('ac-wrapper').style.display = "none";
}
else if(localStorage.getItem("popupWasShown") !== "1" && hideOrshow === 'show') {
document.getElementById('ac-wrapper').removeAttribute('style');
localStorage.setItem("popupWasShown", "1");
}
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 1000);
}
function hideNow(e) {
if (e.target.id == 'ac-wrapper') {
document.getElementById('ac-wrapper').style.display = 'none';
localStorage.setItem("popupWasShown", "1");
}
}
document.getElementById("reset").onclick = function() {
localStorage.setItem("popupWasShown", "3");
}
We have slightly modified the code with session storage in order to load the popup whenever the page is loaded (several times per day or in a new window/tab):
else if(sessionStorage.getItem("popupWasShown") == null) {
sessionStorage.setItem("popupWasShown",1);
document.getElementById('ac-wrapper').removeAttribute('style');
}
Full code:
function PopUp(hideOrshow) {
if (hideOrshow == 'hide') {
document.getElementById('ac-wrapper').style.display = "none";
}
else if(sessionStorage.getItem("popupWasShown") == null) {
sessionStorage.setItem("popupWasShown",1);
document.getElementById('ac-wrapper').removeAttribute('style');
}
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 0);
}
function hideNow(e) {
if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}
**CSS:**
<style>
#popup{
display:none;
}
</style>
**HTML:**
<div id="popup">
<center>
<h2>Popup Content Here</h2>
<input type="button" name="submit" value="Submit"/>
</center>
</div>
**JS:**
<script>
getCookie = function(data){
var dset = data + "=";
var c = document.cookie.split(';');
for(var i=0; i<c.length; i++){
var val = c[i];
while (val.charAt(0)==' ') val = val.substring(1, val.length);
if(val.indexOf(dset) == 0) return val.substring(dset.length, val.length)
}
return "";
}
if(getCookie("popupShow") != "yes"){
document.getElementById('popup').style.display = "block";
//set cookie
document.cookie = 'popupShow=yes; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
}
</script>
Try this one it works on my end;

Fading menus without jQuery

I'm attempting a fading menu system of my own design without the assistance of jQuery. My problem of course is that I can get a menu to fade in or to fade out in a perfect world where the pointer doesn't quickly enter and leave the element that produces the menu (in my case a UL). But naturally I get a flickering effect when the cursor enters and exits the UL quickly. I imagine the need is for a great over-arcing event handler of my own design. I will post my code though I don't think that it will be needed as I'm probably going to scrap it and start over. Does anyone have links/ideas/or a good direction to start in with this?
JavaScript code:
window.onload = InitPage;
function InitPage(){
function fadeEffect(child, opacity, direction, e){
if(direction && opacity != 1){
opacity = opacity < 1?Math.round((opacity + 0.05)*100)/100:1;
child.style.opacity = opacity;
setTimeout(function(){fadeEffect(child, opacity, direction,e)},50);
}else if(!direction && opacity != 0){
opacity = opacity > 0?Math.round((opacity - 0.05)*100)/100:0;
child.style.opacity = opacity;
child.style.display = opacity == 0?"none":"block";
setTimeout(function(){fadeEffect(child, opacity, direction,e)},50);
}
}
function hoverMenu(e, oTarget){
var isChildOf = function(pNode, cNode){
if(pNode === cNode){
return true;
}
while (cNode && cNode !== pNode){
cNode = cNode.parentNode;
}
return cNode === pNode;
}
var hasChildMenu = function(pNode, cNode){
while(cNode && cNode !== pNode){
if(cNode.className == "ul_menu" || cNode.className == "li_menu"){
cNode.style.display = "block";
//cNode.style.opacity = 1;
fadeEffect(cNode,0,true,e);
//cNode.timer = setInterval(function(arg1,arg2,arg3){return function(){fadeEffect(arg1,arg2,arg3)}}(cNode,opacity,true),50);
}
cNode = cNode.previousSibling;
}
if(e.type == "mouseout"){
e.cancelBubble();
}
}
var target = e.target;
if(!oTarget){
oTarget = target;
}
var relTarg = e.fromElement;
if(isChildOf(oTarget, relTarg) == false){
//alert("mouse enters");
hasChildMenu(oTarget, oTarget.lastChild);
}
}
function unhoverMenu(e, oTarget){
var isChildOf = function(pNode, cNode){
//check to see if element is a child
if(pNode === cNode){
return true;
}
while (cNode && cNode !== pNode){
cNode = cNode.parentNode;
}
return cNode === pNode;
}
var hasChildMenu = function(pNode, cNode){
while(cNode && cNode !== pNode){
if(cNode.className == "ul_menu" || cNode.className == "li_menu"){
//cNode.style.opacity = 0;
//cNode.style.display = "none";
fadeEffect(cNode,1,false,e);
}
cNode = cNode.previousSibling;
}
if(e.type == "mouseover"){
e.cancelBubble();
}
}
var target = e.target;
if(!oTarget){
oTarget = target;
}
var relTarg = e.toElement;
if(isChildOf(oTarget, relTarg) == false){
hasChildMenu(oTarget, oTarget.lastChild);
}
function MenuEventHandler (e, oTarget){
}
}
var ul_menu = document.getElementById("ul_grabbed");
ul_menu.addEventListener("mouseover", function(e1){return function(e){hoverMenu(e, e1)}}(ul_menu),false);
ul_menu.addEventListener("mouseout", function(e1){return function(e){unhoverMenu(e, e1)}}(ul_menu),false);
//document.addEventListener("mouseover", hoverMenu,false);
//document.addEventListener("mouseout",unhoverMenu,false);
}
HTML code:
<html>
<head>
<script type="text/javascript" src="bubble.js"></script>
<link rel="stylesheet" href="bubble_style.css" type="text/css" media="screen" />
</head>
<body>
<div id="background">
<div id="menu_section">
<ul id="ul_grabbed" class="ul_menu">Menu 1
<li class="li_menu">item 1</li>
<li class="li_menu">item 2</li>
<li class="li_menu">item 3</li>
<li class="li_menu">item 4</li>
</ul>
<ul class="ul_menu">
Menu 2
</ul>
</div>
</div>
</body>
</html>
CSS code:
*{margin:0; padding:0}
body{margin:0; padding:0;background-color:black}
div#background{
margin: 0 auto 0 auto;
display:block;
width:800px;
height:100%;
vertical-align:middle;
background-color: green;}
div#menu_section{
margin:auto;
width:800px;
height:40px;
background-color:purple;}
div#monkey{
width:400px;
height:400px;
background-color:red;}
ul.ul_menu{
list-style:none;
display:block;
height:40px;
width:400px;
float:left;
text-align:center;
color:white;
}
li.li_menu{
height:20px;
display:none;
position:relative;
text-align:center;
color:white;
background-color:black;
opacity:0;}
In an actual project, doing this without jQuery (or some other library) would make me wonder if you're a glutton for punishment. Cross-browser animation is a relatively hard problem that's already been solved.
However, since this is a learning experience, here are a few pointers:
One place to start would be to examine how jQuery does animations.
You could cheat a little and use CSS3 animations.
I have a solution to this (junk code that it might be). The below code demonstrates what I was trying to learn and perhaps can help others view the same thing.
HTML/CSS
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="test_menu.js"></script>
<style type="text/css" media="screen">
#menu_header{
background-color:#617A2A;
color:#C5DE8E;
height:40px;
width:120px;
text-align:center;
display:block;}
#menu{
opacity:0;
display:none;
position:absolute;
background-color:#AEC971;
width:120px;}
#menu div{
text-align:center;}
#menu a, #menu a:link, #menu a:visited{
color:#FFF;
display:block;
text-decoration:none;}
#menu a:hover{
background-color:#414A2C;}
#info_area{
border: 1px black solid;
position:float-left;
margin-top:20px;
width:512px;
height:512px;
overflow:auto;}
</style>
</head>
<body>
<div id="menu_header">
Something
</div>
<div id="menu">
<div>Google</div>
<div>Yahoo</div>
</div>
<div id="info_area">
</div>
</body>
</html>
Javascript:
window.onload = InitPage;
function InitPage(){
var menu = document.getElementById("menu");
var menu_header = document.getElementById("menu_header");
var opacity_global = menu.style.opacity == ""?0:menu.style.opacity;
var timer = 0;
function fadeEffect(opacity, direction){
if(direction && opacity != 1){
opacity_global = opacity < 1?Math.round((opacity + 0.05)*100)/100:1;
menu.style.opacity = opacity_global;
if(opacity_global == 1){
window.clearInterval(timer);
}
//setTimeout(function(){fadeEffect(child, opacity, direction);},50);
}else if(!direction && opacity != 0){
opacity_global = opacity > 0?Math.round((opacity - 0.05)*100)/100:0;
menu.style.opacity = opacity_global;
menu.style.display = opacity_global == 0?"none":"block";
if(opacity_global == 0){
window.clearInterval(timer);
}
//setTimeout(function(){fadeEffect(child, opacity, direction);},50);
}
}
function eventHandler(e, menu, menu_header){
var target = e.target;
var menu_headerTarget = menu_header;
var menuTarget = menu;
var fromTarget = e.fromElement;
var toTarget = e.toElement;
var info = document.getElementById("info_area");
var isChild = function(pNode, cNode){
while(cNode && pNode !== cNode){
cNode = cNode.parentNode;
}
return pNode === cNode;
}
//alert("e.type: " + e.type + "\ntarget: " + target + "\ntoElement: " + toTarget + "\nfromElement: " + fromTarget );
if((isChild(target, fromTarget) == false) && (e.type == "mouseover") && (isChild(menuTarget,target)==false) && (isChild(menuTarget, fromTarget)==false)){
window.clearInterval(timer);
info.innerHTML += "<br />mouseover!";
menuTarget.style.display = "block";
timer = window.setInterval(function(){return fadeEffect(opacity_global, true);},25);
//menuTarget.timer = setInterval(function(arg){arg.style.opacity += 0.05}(menuTarget),50);
}else if((fromTarget === menu_headerTarget) && (isChild(menuTarget,toTarget) == false) && e.type == "mouseout"){
window.clearInterval(timer);
info.innerHTML += "<br />mouseout 1";
//menuTarget.style.display = "none";
timer = window.setInterval(function(){return fadeEffect(opacity_global, false);},25);
//setTimeout(function(menuTarget){return function(){menuTarget.style.display = "none"}}(menuTarget),1000);
}
else if((isChild(menuTarget, target) == true) && (isChild(menuTarget, toTarget) == false) && (toTarget !== menu_headerTarget) && e.type == "mouseout"){
window.clearInterval(timer);
info.innerHTML += "<br />mouseout 2";
//menuTarget.style.display = "none";
//setTimeout(function(menuTarget){return function(){menuTarget.style.display = "none"}}(menuTarget),1000);
timer = window.setInterval(function(){fadeEffect(opacity_global, false);},25);
}else{
info.innerHTML += "<br />Stopped an event!! " + "type: " + e.type + " target: " + target;
e.stopPropagation();
}
}
menu_header.addEventListener("mouseover",function(e){eventHandler(e, menu, menu_header);},false);
menu_header.addEventListener("mouseout",function(e){eventHandler(e, menu, menu_header);},false);
menu.addEventListener("mouseout",function(e){eventHandler(e, menu, menu_header);},false);
menu.addEventListener("mouseover",function(e){eventHandler(e, menu, menu_header);},false);
}

Categories