Store Animation State When Coming Back To URL - javascript

I have a simple JS scroll event that when an element gets to within 50px of the top of the window the header animates and changes colour, which is done by using getBoundingClientRect().top < 50 on a trigger element. This functionality is only on the home page of the site.
Is there anyway of having it so when a user visits another URL/page on the site, and then comes back to this page via the browsers back arrow, that the previous animation state is still applied? If the page reloads and starts at the top again it doesn't matter, but if you click back to the page that uses this code, the menu transition happens even if you return to part of the page that was past the trigger point. I don't want to force the page to the top each time because this page is going to have downloadable and searchable info on, so that it would be real pain to be sent back to the top of that page each time.
I've given a working example below and via the CodePen link, the problem is of course on CodePen and StackOverflow when you go to a different URL and then click back to URL in question it actually reloads the page from scratch again, which doesn't happen as standard browser behaviour on day-to-day websites.
Codepen: https://codepen.io/anna_paul/pen/bGvPWRj
In that back end I'm using PHP, and I do have access to this is there needs to be a server side solution.
Any ideas or suggestions appreciated.
Note: On the actual site this scroll event is invoked via a debounce function, but I have removed this for code simplicity.
let triggerElement = document.getElementById('trigger-element'),
header = document.getElementById('h')
let menuChange = function() {
if(triggerElement.getBoundingClientRect().top < 50) {
header.style.background = 'black'
header.style.transition = '1s'
} else {
header.style.background = 'red'
header.style.transition = '.15s'
}
}
window.addEventListener('scroll', menuChange)
body {
margin: 0;
height: 200vh;
}
#h {
display: flex;
justify-content: center;
background: red;
color: #fff;
position: fixed;
top: 0;
width: 100%;
}
#trigger-element {
margin-top: 150px;
padding: 1rem;
background:blue;
color: #fff;
}
<header id="h">
<p>HEADER CONTENT</p>
</header>
<div id="trigger-element">Trigger Element</div>

I recommend using localStorage for this particular use case, because it can easily be implemented alongside your current method:
const triggerElement = document.getElementById('trigger-element');
const header = document.getElementById('h');
const animationTriggered = localStorage.getItem('animationTriggered') === 'true';
let initialLoad = true;
const menuChange = function() {
if (animationTriggered && initialLoad) {
header.style.background = 'black';
} else if (triggerElement.getBoundingClientRect().top < 50) {
header.style.background = 'black';
header.style.transition = '1s';
localStorage.setItem('animationTriggered', 'true');
} else {
header.style.background = 'red';
header.style.transition = '.15s';
localStorage.setItem('animationTriggered', 'false');
}
initialLoad = false;
}
window.addEventListener('scroll', menuChange);
This will remember the previous state and apply the black background color if the animation was previously triggered. This adds a small amount of overhead, but in a real-world scenario it should not have any noticeable impact on the performance of the application.

Related

Deduct Timer Count Every Page Refresh (Vanilla Javascript)

I am absolutely a noob when it comes to Javascript so I hope someone can help me please. I made a very simple Vanilla JS + HTML code that counts the number of times that it reaches 10 seconds (10 seconds = 1 count). This code will also refresh the page onmouseleave and when I change tab using window.onblur. My problem is that every time the page refreshes, the counter will go back to zero. What I want is that for the counter to deduct just one (or a specific number of) count every page refresh instead of completely restarting the count to zero. Please help me with Vanilla Javascript only and no JQuery (because I am planning to use this code personally and offline). Thank you in advance.
For those who may wonder what's this code is for, I want to create this to encourage myself to stay away from my computer for a certain period everyday. Like, if I can stay away from my computer for 100 counts, then I can use my computer freely after. I am addicted to the internet and I want to make this as my own personal way of building self-control.
Here is my code:
<style>
label {
color: orange;
}
p {
border-radius: 0px;
color: black;
text-decoration: none;
font-family: Consolas !important;
font-size: 16px;
font-weight: normal;
outline: none;
line-height: 0.25 ;
}
</style>
<body onmouseleave="window.location.reload(true)">
<p>You have earned <label id="pointscounter">00</label> point/s.</p>
<script>
var PointsLabel = document.getElementById("pointscounter");
var totalCountPoints = 0;
setInterval(setTimePoints, 10000);
function setTimePoints() {
++totalCountPoints;
PointsLabel.innerHTML = pad(totalCountPoints);
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
</script>
<script>
var blurred = false;
window.onblur = function() { blurred = true; };
window.onfocus = function() { blurred && (location.reload()); };
</script>
</body>
Storage
If you want the data to survive a reload, you need to save it somewhere. There are multiple options you can use. I used localStorage. You can learn more about it here: https://www.w3schools.com/jsref/prop_win_localstorage.asp. localStorage even survives closing the Browser Tab.
If you want to reset the data in a new session, you can use sessionStorage (just replace localStorage with sessionStorage): https://www.w3schools.com/jsref/prop_win_sessionstorage.asp.
What I did:
Save data on blur
If a blur-event occurs, the data is saved.
I also stopped the interval because there is no need for the interval anymore.
blurred variable
There is (currently?) no need for this variable.
The only usecase seems to be:
window.onfocus = function() {
blurred && location.reload();
};
To my knowledge you don't need this variable here.
Comming back
If the user already has points in localstorage, the current Points are calculated based on the points in localstorage. It currently deducts 1 point.
Using onmouseleave
I replaced the location.reload(true) on the body-tag with a function call. Everytime the mouse leaves, it calls this function. This function calls the onBlur function. The onBlur function is there, to ensure, that both window.onblur and onmouseleave do the same thing (save & stop). After the onBlur function is called, an EventListener is added to wait for mouseenter. When the mouse is seen again, we can reload the page with the onFocus function. It wouldn't reload the page as soon as the mouse left, because the timer would start (bc of reload), even if the mouse wasn't on the document.
Todo:
There is currently no check to see, if a the mouse in on the document after a reload. The timer will begin, even if the mouse isn't on the document.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
label {
color: orange;
}
p {
border-radius: 0px;
color: black;
text-decoration: none;
font-family: Consolas !important;
font-size: 16px;
font-weight: normal;
outline: none;
line-height: 0.25;
}
</style>
</head>
<body onmouseleave="mouseLeft()">
<p>You have earned <label id="pointscounter">00</label> point/s.</p>
<script>
var PointsLabel = document.getElementById("pointscounter");
var totalCountPoints = 0;
// Calculate Points if user has already collected points
if (localStorage.getItem("points") !== null) {
// You can change, how many points to deduct
const pointsToDeduct = 1;
var tempPoints = localStorage.getItem("points");
totalCountPoints = tempPoints - pointsToDeduct;
// Reset to 0 if points now negative
if (totalCountPoints < 0) {
totalCountPoints = 0;
}
PointsLabel.innerHTML = pad(totalCountPoints);
}
// need to save, to stop/clear it later
var timePointsInterval = setInterval(setTimePoints, 10000);
function setTimePoints() {
++totalCountPoints;
PointsLabel.innerHTML = pad(totalCountPoints);
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
function mouseLeft() {
onBlur();
document.addEventListener("mouseenter", onFocus);
}
function onBlur() {
// save Current Points:
localStorage.setItem("points", totalCountPoints);
//stop the timer
clearInterval(timePointsInterval);
}
function onFocus() {
location.reload();
}
// Blur Detection
var blurred = false;
window.onblur = function () {
// [-] blurred = true;
onBlur();
};
window.onfocus = function () {
// [-] blurred && location.reload();
onFocus();
};
</script>
</body>
</html>

Force browser to immediately repaint a dom element

I need to insert a huge html markup to some dom element which will take awhile. It is a reason why I want to display some preloader indicator. I have two blocks: #preloader and #container. Some code displays the preloader firstly and then starts to paste a big html markup.
The problem - preloader hasn't really displayed until browser will not finish render html markup. I've tried a lot of solutions (a lot of them are described here) but still haven't success.
An example is avalable below:
https://jsfiddle.net/f9f5atzu/
<div id='preloader'>Preloader...</div>
<div id='container'>Container...</div>
#preloader {
display: none;
background-color: #f00;
color: #fff;
hight: 100px;
text-align: center;
padding: 10px 20px;
}
#container {
background-color: #ccc;
}
setTimeout(function() {
// Define variables
let domPreloader = document.getElementById('preloader');
let domContainer = document.getElementById('container');
const html = Array(100000).fill("<div>1</div>");
// Display preloader
domPreloader.style.display = 'hide';
domPreloader.offsetHeight;
domPreloader.style.webkitTransform = 'scale(1)';
domPreloader.style.display = 'block';
// Render a big html
domContainer.innerHTML = html;
}, 1000);
Is there any solutions for the problem?
The way you did it, you're not releasing control to the browser between the display of the preloader and the display of the 'big html'.
Rather than encapsulating this whole block inside a setTimeout(), you should just differ the rendering part.
Please try something along those lines:
// Define variables
let domPreloader = document.getElementById('preloader');
let domContainer = document.getElementById('container');
// Display preloader
domPreloader.style.webkitTransform = 'scale(1)';
domPreloader.style.display = 'block';
// Render a big html
setTimeout(render, 100);
function render() {
const html = Array(100000).fill("<div>1</div>");
domContainer.innerHTML = html;
// Hide preloader
domPreloader.style.display = 'none';
}
JSFiddle

Changing parent css on child focus (without breaking parent:hover css rules)

I made a menu on html (on the side and 100% heigth, expandeable as in android holo)
<div id="menu">
<button class="menubutton"></button>
<button class="menubutton"></button>
</div>
The menu normally remains transparent and with a short width:
#menu {
background-color: transparent;
width: 8%;
}
The idea was to expand and color it on hover. It was easy:
#menu:hover {
background-color: blue;
width: 90%;
}
There is no problem untill here. I need the same effect on focus. There is no way in css to change parent css on child focus (neither hover by the way, but it is not needed, cuase i can use the entire menu hover).
So i used a script:
var menubuttonfocus = document.getElementsByClassName("menubutton");
for (i=0; i<menubuttonfocus.length; i++) {
menubuttonfocus[i].addEventListener("focus", function() {
menu.style.backgroundColor = "blue";
menu.style.width = "90%";
});
menubuttonfocus[i].addEventListener("blur", function() {
menu.style.backgroundColor = "transparent";
menu.style.width = "8%";
});
}
The script works just fine, the problem is that when you trigger those events by focusing a button, the css of #menu:hover changes somehow and #menu does not change when hovering. I tried to solve this by doing something similar but with hover instead of focus:
menu.addEventListener("mouseenter", function(){
menu.style.backgroundColor = "blue";
menu.style.width = "90%";
});
menu.addEventListener("mouseout", function(){
menu.style.backgroundColor = "transparent";
menu.style.width = "8%";
});
This works somehow, but it is REALLY buggy.
I tried also to select "#menu:hover,#menu:focus", but it doesn't work because the focus is on the button elements and not in #menu.
Please avoid jquery if posible, and i know it's asking for too much but a pure css solution would be awesome.
Probably helpful info: html element are created dinamically with javascript.
I can show more code or screenshot, you can even download it (it is a chrome app) if needed: chrome webstore page
Thanks.
SOLVED: I did what #GCyrillus told me, changing #menu class on focus via javascript eventListener. .buttonbeingfocused contains the same css as "#menu:hover". Here is the script:
var menubuttonfocus = document.getElementsByClassName("menubutton");
for (i=0; i<menubuttonfocus.length; i++) {
menubuttonfocus[i].addEventListener("focus", function() {
menu.classList.add("buttonbeingfocused");
});
menubuttonfocus[i].addEventListener("blur", function() {
menu.classList.remove("buttonbeingfocused");
});
}
if the problem is what I think it is - you forgetting about one thing:
When you focusing / mouseentering the .menubutton - you are mouseleaving #menu and vice-versa - so your menu behaviour is unpredictible because you want to show your menu and hide it at the same time.
solution is usually setting some timeout before running "hiding" part of the script, and clearing this timeout (if exist) when running "showing" part.
it will be something like this:
var menuTimeout;
function showMenu() {
if (menuTimeout) clearTimeout(menuTimeout);
menu.style.backgroundColor = "blue";
menu.style.width = "90%";
}
function hideMenu() {
menuTimeout = setTimeout( function() {
menu.style.backgroundColor = "transparent";
menu.style.width = "8%";
}, 800);
}
//then add your listeners like you did - but put these functions as a handlers - like this:
menu.addEventListener("mouseenter", showMenu);
...
//in addition you need also "mouseenter" and "mouseleave" events handled on .menubuttons

changing CSS elements with javascript for same element id in multiple places

Okay so im pretty new to html/javascript/css through some tutorials and this site it's coming along. I am attempting to display a button which i use css to overlay with an image when the button is clicked I call a javascript function to send some info to my server as well as replace the button which was clicked with a new button and image overlay. here is the code snippets responsible for this (I'm basically just toggling the visibility on the buttons back and forth):
<style type = 'text/css'>
input.btn_follow {
position: absolute;
right: 2px;
top: 2px;
background-image: url(http://icons.iconarchive.com/icons/icojam/onebit/48/star-100-icon.png); /* 16px x 16px */
}
input.btn_unfollow {
visibility: hidden;
position: absolute;
right: 2px;
top: 2px;
background-image: url(http://gologic.com/imagesOld/checkmark%20-%20small.png);
}
</style>
</head><body>
<script type='text/javascript'>
function follow(series, status) {
var xhReq = new XMLHttpRequest();
var request = "follow.php?series="+series+"&status="+status
xhReq.open("GET", request, false);
xhReq.send(null);
var response = xhReq.responseText;
var IDyes = "follow_"+series
var IDno = "unfollow_"+series
if (response == 1){
document.getElementById(IDyes).style.visibility='hidden'
document.getElementById(IDno).style.visibility='visible'
}
else if (response == 0){
document.getElementById(IDyes).style.visibility='visible'
document.getElementById(IDno).style.visibility='hidden'
}
else if (response == -1){
alert("you must first login to use the follow request"); // now following show
}
}
</script>
So all of this kind of works, however for some element ID's they appear multiple times on the same html page. If this is the case only the first instance of the element is the visibility is changed and not for the rest. why is this if they have the same id ? how can I fix this? here is a link to see this in action on my web page to make this more clear http://ec2-54-234-192-222.compute-1.amazonaws.com/home.php (the button's in question are the stars)
any help would be greatly appreciated (also if there is a cleaner way scraping what i Have i'd be open to as already starting to resemble spaghetti!)
thanks -brendan
So as in the comments above Id's should only appear once per page! I'm blaming this on being a newb thanks to #Jeff shaver for clarrifying this

lightbox--> what's under the hood? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have never used a lightbox before, but recently started thinking about using a similar feature on my website. I found a ton of jquery libraries and various add-ons, but I am a big fan of writing my own code. When I started looking under the hood, I was surprised to realize that it appears to simply be a hidden html element that is displayed when a Javascript event listener is triggered. Am I right about this? Is there more than meets the eye?
Just wondering how it works. Thank you in advance for your consideration.
UPDATE
Great answers! I went with Ana's response because the other considerations regarding the design go without saying. As far as the mechanisms, it really does appear to be a wonderfully understated device. Thanks to all who read, commented, and replied...
No, there really is not much more to it. However, I don't really see the point of having the HTML element there from the beginning unless you don't want to use JavaScript for your lightbox, which I don't think it is the case here judging from your tags and which I'm not a fan of using in real projects, even though I think it is really cool that it can be done.
If you're using JavaScript anyway in order to display the lightbox (which means that if JavaScript is disabled, your lightbox won't get displayed even if it is there, loaded right from the beginning... so why load it if you can't display it?), then it's probably better to just create the lightbox element (and everything in it, and then append it to the page) only when you first want the lightbox to open.
What I mean by that is that you attach a click handler to the links (actually, I would attach it to the container an then check what was clicked, if it is a link, see what link it is and go further) and check whether you have a lightbox element. If you don't, then you create it on the spot. If you already do, then you simply display it with whatever you need in it for that particular link that was clicked.
A basic lightbox example for an image gallery.
The HTML structure of the gallery would be:
<section class='gallery' id='gallery'>
<a href='images/large_0.jpg' class='thumb'>
<img class='thumb-img' src='images/small_0.jpg'>
</a>
<!-- as many more as you wish -->
</section>
The CSS:
/* gallery with thumbnails */
.gallery { text-align: center; }
.gallery .thumb, .gallery .thumb-img {
display: inline-block;
width: 10em;
height: 5.6em;
}
/* lightbox */
.lightbox {
z-index: 999; /* some ridiculously large value to make sure it's on top */
position: fixed;
top: 0; right: 0; bottom: 0; left: 0;
background: rgba(0,0,0,.5);
cursor: pointer;
text-align: center;
}
.lightbox:before { /* strictly for vertical centering of large image */
display: inline-block;
height: 100%;
vertical-align: middle;
content: '';
}
/* add/ remove this class to toggle display */
.hidden { display: none; }
.large { /* the large image */
max-width: 100%;
max-height: 100%;
vertical-align: middle;
}
The JavaScript:
var g = document.getElementById('gallery');
String.prototype.endsIn = function(suffixes) { /*just to check the extension*/
for(i in suffixes) {
if(this.indexOf(suffixes[i], this.length - suffixes[i].length) !== -1)
return true;
}
return false;
};
g.addEventListener('click', function(e){
var target = e.target, lnk, ext = ['.jpg', '.png'], lightbox, large;
if(!target.classList.contains('thumb-img')) return;
else {
lnk = target.parentNode.href;
if(!lnk.endsIn(ext)) return;
else {
lightbox = document.getElementById('lightbox');
if(lightbox == null) {
lightbox = document.createElement('div');
lightbox.setAttribute('id', 'lightbox');
lightbox.classList.add('lightbox');
lightbox.innerHTML = "<img src='"+ lnk +"' id='large' class='large'>";
document.body.appendChild(lightbox);
lightbox.addEventListener('click', function(ev) {
var target = ev.target, next, links = g.querySelectorAll('.thumb'),
len = links.length, large = document.getElementById('large');
if(target.id == 'lightbox') lightbox.classList.add('hidden');
else if(target.id == 'large') {
for(var i = 0; i < len; i++) {
if(links[i].href == large.src) {
next = links[(i++)%len].href;
while(!next.endsIn(ext)) next = links[(i++)%len].href;
large.src = links[i%len].href;
break;
}
}
}
}, false);
}
else {
lightbox.classList.remove('hidden');
large = document.getElementById('large');
large.src = lnk;
}
e.preventDefault();
}
}
}, false);

Categories