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);
}
Related
anchorArrows is an element that if I click the checkbox it must be shown and if it's not checked it must be hidden. The classList hidden and show are CSS classes with opacity 0 and 1
let q = document.getElementById("Q").value;
let q2 = document.getElementById("q2").value;
const anchorArrows = document.getElementById("anchor");
if((chkQ.checked == true) && (chkQ2.checked == false)){
anchorArrows.classList.add("show");
anchorArrows.classList.remove("hidden");
if(q > 0){
flechas(0,"x");
}else{
flechas(180,"x");
}
}else{
anchorArrows.classList.remove("show");
anchorArrows.classList.add("hidden");
}
if((chkQ2.checked == true) && (chkQ.checked == false)){
anchorArrows.classList.add("show");
anchorArrows.classList.remove("hidden");
if(q > 0){
flechas(0,"y");
}else{
flechas(180,"y");
}
}else{
anchorArrows.classList.remove("show");
anchorArrows.classList.add("hidden");
}
CSS:
.hidden{
opacity: 0;
}
.show{
opacity: 1;
}
You need to use else if and one else. The issue you have is the first if can be true, but the second else will wipe away the class.
if (chkQ.checked && !chkQ2.checked) {
anchorArrows.classList.add("show");
anchorArrows.classList.remove("hidden");
if (q > 0) {
flechas(0, "x");
} else {
flechas(180, "x");
}
} else if (chkQ2.checked && !chkQ.checked) {
anchorArrows.classList.add("show");
anchorArrows.classList.remove("hidden");
if (q > 0) {
flechas(0, "y");
} else {
flechas(180, "y");
}
} else {
anchorArrows.classList.remove("show");
anchorArrows.classList.add("hidden");
}
And to get rid of repeated code
let isValid = false;
if ((!chkQ.checked && chkQ2.checked) || (chkQ.checked && !chkQ2.checked)) {
isValid = true;
const num = +q > 0 ? 0 : 180;
const code = chkQ.checked ? "x" : "y";
flechas(num, code);
}
anchorArrows.classList.toggle("show", isValid);
anchorArrows.classList.toggle("hidden", !isValid);
Personally, I wouldn't use classes to change opacity, as multiple variables can affect the outcome of it. Instead, I would put opacity in the original Id/Class in the CSS, and use .style.opacity to change it.
For Example:
CSS:
#box {
opacity:1;
}
HTML:
<div id="box"></div>
Javascript:
document.getElementById('box').style.opacity = .5;
In your code, it would be anchorArrows.style.opacity = 1; for show, and anchorArrows.style.opacity = 0; for hidden.
There are spans in the content editable div which needs to be deleted all at once. Now this works fine on the chrome desktop but when I try to delete it on the following devices this does not works.I am testing it on following
Chrome on Android
Safari on Mac, iOS
Firefox on Windows
When I try to delete the box looses focus and span does not delete.
This is the fiddle link to what I have tried so far.
var EditableDiv = document.getElementById('EditableDiv');
EditableDiv.onkeydown = function(event) {
var ignoreKey;
var key = event.keyCode || event.charCode;
if (!window.getSelection) return;
var selection = window.getSelection();
var focusNode = selection.focusNode,
anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
if (!anchorNode) return
if (anchorNode.nodeName.toLowerCase() != '#text') {
if (anchorOffset < anchorNode.childNodes.length)
anchorNode = anchorNode.childNodes[anchorOffset]
else {
while (!anchorNode.nextSibling) anchorNode = anchorNode.parentNode // this might step out of EditableDiv to "justincase" comment node
anchorNode = anchorNode.nextSibling
}
anchorOffset = 0
}
function backseek() {
while ((anchorOffset == 0) && (anchorNode != EditableDiv)) {
if (anchorNode.previousSibling) {
if (anchorNode.previousSibling.nodeName.toLowerCase() == '#text') {
if (anchorNode.previousSibling.nodeValue.length == 0)
anchorNode.parentNode.removeChild(anchorNode.previousSibling)
else {
anchorNode = anchorNode.previousSibling
anchorOffset = anchorNode.nodeValue.length
}
} else if ((anchorNode.previousSibling.offsetWidth == 0) && (anchorNode.previousSibling.offsetHeight == 0))
anchorNode.parentNode.removeChild(anchorNode.previousSibling)
else {
anchorNode = anchorNode.previousSibling
while ((anchorNode.lastChild) && (anchorNode.nodeName.toUpperCase() != 'SPAN')) {
if ((anchorNode.lastChild.offsetWidth == 0) && (anchorNode.lastChild.offsetHeight == 0))
anchorNode.removeChild(anchorNode.lastChild)
else if (anchorNode.lastChild.nodeName.toLowerCase() != '#text')
anchorNode = anchorNode.lastChild
else if (anchorNode.lastChild.nodeValue.length == 0)
anchorNode.removeChild(anchorNode.lastChild)
else {
anchorNode = anchorNode.lastChild
anchorOffset = anchorNode.nodeValue.length
//break //don't need to break, textnode has no children
}
}
break
}
} else
while (((anchorNode = anchorNode.parentNode) != EditableDiv) && !anchorNode.previousSibling) {}
}
}
if (key == 8) { //backspace
if (!selection.isCollapsed) {
try {
document.createElement("select").size = -1
} catch (e) { //kludge for IE when 2+ SPANs are back-to-back adjacent
if (anchorNode.nodeName.toUpperCase() == 'SPAN') {
backseek()
if (anchorNode.nodeName.toUpperCase() == 'SPAN') {
var k = document.createTextNode(" ") // doesn't work here between two spans. IE makes TWO EMPTY textnodes instead !
anchorNode.parentNode.insertBefore(k, anchorNode) // this works
anchorNode.parentNode.insertBefore(anchorNode, k) // simulate "insertAfter"
}
}
}
} else {
backseek()
if (anchorNode == EditableDiv)
ignoreKey = true
else if (anchorNode.nodeName.toUpperCase() == 'SPAN') {
SelectText(event, anchorNode)
ignoreKey = true
} else if ((anchorNode.nodeName.toLowerCase() == '#text') && (anchorOffset <= 1)) {
var prev, anchorNodeSave = anchorNode,
anchorOffsetSave = anchorOffset
anchorOffset = 0
backseek()
if (anchorNode.nodeName.toUpperCase() == 'SPAN') prev = anchorNode
anchorNode = anchorNodeSave
anchorOffset = anchorOffsetSave
if (prev) {
if (anchorOffset == 0)
SelectEvent(prev)
else {
var r = document.createRange()
selection.removeAllRanges()
if (anchorNode.nodeValue.length > 1) {
r.setStart(anchorNode, 0)
selection.addRange(r)
anchorNode.deleteData(0, 1)
}
else {
for (var i = 0, p = prev.parentNode; true; i++)
if (p.childNodes[i] == prev) break
r.setStart(p, ++i)
selection.addRange(r)
anchorNode.parentNode.removeChild(anchorNode)
}
}
ignoreKey = true
}
}
}
}
if (ignoreKey) {
var evt = event || window.event;
if (evt.stopPropagation) evt.stopPropagation();
evt.preventDefault();
return false;
}
}
function SelectText(event, element) {
var range, selection;
EditableDiv.focus();
if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNode(element)
selection.removeAllRanges();
selection.addRange(range);
} else {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
}
var evt = (event) ? event : window.event;
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble != null) evt.cancelBubble = true;
return false;
}
#EditableDiv {
height: 75px;
width: 500px;
font-family: Consolas;
font-size: 10pt;
font-weight: normal;
letter-spacing: 1px;
background-color: white;
overflow-y: scroll;
overflow-x: hidden;
border: 1px solid black;
padding: 5px;
}
#EditableDiv span {
color: brown;
font-family: Verdana;
font-size: 8.5pt;
min-width: 10px;
/*_width: 10px;*/
/* what is this? */
}
#EditableDiv p,
#EditableDiv br {
display: inline;
}
<div id="EditableDiv" contenteditable="true">
(<span contenteditable='false' onclick='SelectText(event, this);' unselectable='on'>Field1</span> < 500) <span contenteditable='false' onclick='SelectText(event, this);' unselectable='on'>OR</span> (<span contenteditable='false' onclick='SelectText(event, this);' unselectable='on'>Field2</span> > 100 <span contenteditable='false' onclick='SelectText(event, this);' unselectable='on'>AND</span> (<span contenteditable='false' onclick='SelectText(event, this);' unselectable='on'>Field3</span> <= 200) )
</div>
I am using javascript for this.
I am developing a solution for a app using meteor and blaze UI for templates which will run on iOS.
Try to put the css cursor:pointer; on the div that you want to click on and delete.
Sometimes mobile browser, esp. Safari doesnt allow click event on the element unless it has cursor:pointer. It will trigger that this div is link or clickable.
I am coding a page that increments the CSS top and left properties in order to simulate an animation with two stars moving around a button. I calculated the measurements, and it looked fine at first. However, after several minutes, the stars become desynchronized, and don't change animation at the same time. They should be reaching a corner at the same time. Can someone please explain why this is, and how I could fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/1503x4tr/12/
And here is my code:
body {
margin:0px;
}
.heading {
text-align:center;
font-family:'Bungee Shade', Courier New, Courier, Lucida Sans Typewriter, Lucida Typewriter, monospace;
color:green;
font-weight:bold;
font-size:30px;
margin-top:0px;
}
.text {
color:red;
font-family:'Josefin Sans', Futura, Trebuchet MS, Arial, sans-serif;
font-size:21px;
text-align:justify;
margin-top:-15px;
}
br {
line-height:500%;
}
.container {
position:relative;
width:350px;
height:350px;
margin-top:42px;
margin-left:auto;
margin-right:auto;
}
.star {
width:40px;
height:40px;
position:absolute;
}
#starOne {
top:0px;
left:0px;
}
#starTwo {
top:310px;
left:310px;
}
.button {
width:250px;
height:250px;
border-style:solid;
border-color:red;
border-width:5px;
border-radius:60px;
text-align:center;
position:absolute;
bottom:50px;
left:50px;
}
.button:hover {
background-color: #7CFC00;
cursor:pointer
}
.button-text {
font-family:'Righteous', Courier New;
color:#9400D3;
font-size:76px;
line-height:125%;
}
#compliment {
text-align:center;
font-family:'VT323', Candara, Calibri, Segoe, Segoe UI, Optima, Arial, sans-serif;
color:#ffd400;
font-size:50px;
}
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Complement.css">
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Bungee+Shade|Josefin+Sans|VT323|Righteous">
<title>The Compliment Machine</title>
</head>
<body>
<h2 class="heading">The Compliment Machine</h2>
<p class="text">In the interest of spreading holiday cheer, I have designed this website with one goal in mind. Pressing the button below will randomly generate a compliment. Hopefully, this little experiment will brighten up your day.</p>
<div class="container" id="container">
<img src="Star.png" class="star" id="starOne">
<div class="button" onclick="timedFunction()" onmouseenter="startingFunction(), startingFunction2()" onmouseleave="endFunction()"> <span class="button-text">Click me!</span> </div>
<img src="Star.png" class="star" id="starTwo">
</div>
<br>
<p id="compliment"></p>
<script>
var userName = prompt("What is your name?");
var generatedUserName = userName === null || userName === "";
var compliment = [
"Have a nice day",
"you contribute to society",
"Always be yourself",
"you are a wonderful person",
"Keep up the good work",
"never stop believing in yourself",
"you have a great sense of humor",
"You should feel proud of yourself",
"Never stop trying",
"you are a winner"
];
</script>
<script>
function timedFunction() {
document.getElementsByTagName("DIV")[0].style.display = "none";
document.getElementsByTagName("DIV")[1].style.display = "none";
document.getElementsByTagName("IMG")[0].style.display = "none";
document.getElementsByTagName("IMG")[1].style.display = "none";
var repeater = setInterval(inspiration, 1000);
}
var inspiration = function inspire() {
var result = Math.random();
//This code block checks for null, undefined, and other falsy values in the prompt.
if (generatedUserName) {
if (0 <= result && result < 0.11) {
userName = "my friend";
}
if (0.21 <= result && result < 0.31) {
userName = "my friend";
}
if (0.41 <= result && result < 0.51) {
userName = "my friend";
}
if (0.71 <= result && result < 0.81) {
userName = "my friend";
}
if (0.81 <= result && result < 0.91) {
userName = "my friend";
}
if (0.11 <= result && result < 0.21) {
userName = "My friend";
}
if (0.31 <= result && result < 0.41) {
userName = "My friend";
}
if (0.51 <= result && result < 0.61) {
userName = "My friend";
}
if (0.61 <= result && result < 0.71) {
userName = "My friend";
}
if (0.91 <= result && result < 1) {
userName = "My friend";
}
}
//This code block changes the sentence with ID 'compliment' randomly, based on the value of the variable 'result'.
if (0 <= result && result < 0.11) {
document.getElementById("compliment").innerHTML = compliment[0]+", "+userName+"!";
};
if (0.11 <= result && result < 0.21) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[1]+".";
};
if (0.21 <= result && result < 0.31) {
document.getElementById("compliment").innerHTML = compliment[2]+", "+userName+".";
};
if (0.31 <= result && result < 0.41) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[3]+".";
};
if (0.41 <= result && result < 0.51) {
document.getElementById("compliment").innerHTML = compliment[4]+", "+userName+"!";
};
if (0.51 <= result && result < 0.61) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[5]+".";
};
if (0.61 <= result && result < 0.71) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[6]+".";
};
if (0.71 <= result && result < 0.81) {
document.getElementById("compliment").innerHTML = compliment[7]+", "+userName+".";
};
if (0.81 <= result && result < 0.91) {
document.getElementById("compliment").innerHTML = compliment[8]+", "+userName+".";
};
if (0.91 <= result && result < 1) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[9]+".";
};
}
var i = 0;
function limitedFunction() {
inspiration();
i++;
if (i === 5) {
document.getElementsByTagName("DIV")[0].style.display = "none";
document.getElementsByTagName("DIV")[1].style.display = "none";
document.getElementsByTagName("IMG")[0].style.display = "none";
document.getElementsByTagName("IMG")[1].style.display = "none";
}
}
</script>
<script>
var starOne = document.getElementById("starOne");
var starTwo = document.getElementById("starTwo");
var posLeft = 0;
var posTop = 0;
var posLeft2 = 310;
var posTop2 = 310;
var startingFunction = function starterFunction() {
toRight = setInterval(moveRight, 1);
}
var startingFunction2 = function starterFunction2() {
toLeft = setInterval(moveLeft, 1);
}
//The following four functions apply to the first star, which begins at the top-left.
function moveRight() {
posLeft++;
starOne.style.left = posLeft + 'px';
if (starOne.style.left === "310px") {
clearInterval(toRight);
toBottom = setInterval(moveDown, 1);
}
}
function moveDown() {
posTop++;
starOne.style.top = posTop + 'px';
if (starOne.style.top === "310px") {
clearInterval(toBottom);
toLeft2 = setInterval(moveLeft2, 1);
}
}
function moveLeft2() {
posLeft--;
starOne.style.left = posLeft + 'px';
if (starOne.style.left === "0px") {
clearInterval(toLeft2);
toTop2 = setInterval(moveUp2, 1);
}
}
function moveUp2() {
posTop--;
starOne.style.top = posTop + 'px';
if (starOne.style.top === "0px") {
clearInterval(toTop2);
startingFunction();
}
}
//The following four functions apply to the second star, which begins at the bottom-right.
function moveLeft() {
posLeft2--;
starTwo.style.left = posLeft2 + 'px';
if (starTwo.style.left === "0px") {
clearInterval(toLeft);
toTop = setInterval(moveUp, 1);
}
}
function moveUp() {
posTop2--;
starTwo.style.top = posTop2 + 'px';
if (starTwo.style.top === "0px") {
clearInterval(toTop);
toRight2 = setInterval(moveRight2, 1);
}
}
function moveRight2() {
posLeft2++;
starTwo.style.left = posLeft2 + 'px';
if (starTwo.style.left === "310px") {
clearInterval(toRight2);
toBottom2 = setInterval(moveDown2, 1);
}
}
function moveDown2() {
posTop2++;
starTwo.style.top = posTop2 + 'px';
if (starTwo.style.top === "310px") {
clearInterval(toBottom2);
startingFunction2();
}
}
//The following function cancels the animation when the mouse leaves the button.
function endFunction() {
//The following four if statements apply to the first star, which begins in the top-left.
if (0 <= posLeft && posLeft <= 310 && posTop === 0) {
clearInterval(toRight);
}
if (0 <= posTop && posTop <= 310 && posLeft === 310) {
clearInterval(toBottom);
}
if (0 <= posLeft && posLeft <= 310 && posTop === 310) {
clearInterval(toLeft2);
}
if (0 <= posTop && posTop <= 310 && posLeft === 0) {
clearInterval(toTop2);
}
//The following four if statements apply to the second star, which begins in the bottom-right.
if (0 <= posLeft2 && posLeft2 <= 310 && posTop2 === 310) {
clearInterval(toLeft);
}
if (0 <= posTop2 && posTop2 <= 310 && posLeft2 === 0) {
clearInterval(toTop);
}
if (0 <= posLeft2 && posLeft2 <= 310 && posTop2 === 0) {
clearInterval(toRight2);
}
if (0 <= posTop2 && posTop2 <= 310 && posLeft2 === 310) {
clearInterval(toBottom2);
}
posLeft = 0;
posTop = 0;
posLeft2 = 310;
posTop2 = 310;
starOne.style.top = posTop + 'px';
starOne.style.left = posLeft + 'px';
starTwo.style.top = posTop2 + 'px';
starTwo.style.left = posLeft2 + 'px';
}
</script>
</body>
</html>
How about you use an alternative approach i.e. use css animation property for the animation and don't use setInterval at all.
Use the keyframes and animate the stars on hover. Here is the working example
var starOne = document.getElementById("starOne");
var starTwo = document.getElementById("starTwo");
var posLeft = 0;
var posTop = 0;
var posLeft2 = 310;
var posTop2 = 310;
document.getElementById("btn").addEventListener("mouseover",function(){
starOne.classList.add("topStarAnimate");
starTwo.classList.add("bottomStarAnimate");
});
document.getElementById("btn").addEventListener("mouseleave",function(){
starOne.classList.remove("topStarAnimate");
starTwo.classList.remove("bottomStarAnimate");
});
body {
margin:0px;
}
.heading {
text-align:center;
font-family:'Bungee Shade', Courier New, Courier, Lucida Sans Typewriter, Lucida Typewriter, monospace;
color:green;
font-weight:bold;
font-size:30px;
margin-top:0px;
}
.text {
color:red;
font-family:'Josefin Sans', Futura, Trebuchet MS, Arial, sans-serif;
font-size:21px;
text-align:justify;
margin-top:-15px;
}
br {
line-height:500%;
}
.container {
position:relative;
width:350px;
height:350px;
margin-top:42px;
margin-left:auto;
margin-right:auto;
}
.star {
width:40px;
height:40px;
position:absolute;
}
#starOne {
top:0px;
left:0px;
}
#starTwo {
top:310px;
left:310px;
}
#keyframes topstar {
0%,100%{
top:0px;
left:0px;
}
25%{
top:0px;
left:310px;
}
50%{
top:310px;
left:310px;
}
75%{
top:310px;
left:0px;
}
}
#keyframes bottomstar {
0%,100%{
top:310px;
left:310px;
}
25%{
top:310px;
left:0px;
}
50%{
top:0px;
left:0px;
}
75%{
top:0px;
left:310px;
}
}
.topStarAnimate{
animation: topstar 4s infinite;
}
.bottomStarAnimate{
animation: bottomstar 4s infinite;
}
.button {
width:250px;
height:250px;
border-style:solid;
border-color:red;
border-width:5px;
border-radius:60px;
text-align:center;
position:absolute;
bottom:50px;
left:50px;
}
.button:hover {
background-color: #7CFC00;
cursor:pointer
}
.button-text {
font-family:'Righteous', Courier New;
color:#9400D3;
font-size:76px;
line-height:125%;
}
<!DOCTYPE html>
<title>The Compliment Machine</title>
<body>
<div class="container" id="container">
<img src="Star.png" class="star" id="starOne">
<div class="button" onclick="timedFunction()" id="btn"> <span class="button-text">Click me!</span> </div>
<img src="Star.png" class="star" id="starTwo">
</div>
<br>
<p id="compliment"></p>
</body>
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;
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