Refresh Page but keep scoll position with countdown timer - javascript

So I have this bit of code which refresh the page after the countdown timer has reached 0. The countdown is displayed in a div at the bottom.
<script>
(function countdown(remaining) {
if(remaining === 0)
location.reload(true);
document.getElementById('countdown').innerHTML = remaining;
setTimeout(function(){ countdown(remaining - 1); }, 1000);
})(60);
</script>
<span id="countdown" class="bold"></span>
I would like it to refresh the same way but keep the scroll position on the browser as the page is pretty long. Would this be possible with this code?
Please give example as I don't understand javascript all that much..
Thanks

Have you used localStorage or cookies before? These are handy parts of your user's browsers where you can actually store and save custom bits of data, just for them. See localStorage API for some more info.
Anyways, you could use localStorage, and then when your user scrolls you could just store how far down they were. Then, on page load, if that localStorage key has a value, scroll the user down that far.
I made a snippet but, sadly, their iframe for snippets won't allow me to access localStorage to actually show you how it works in action. But, I did put some lines in there anyways (untested, though) with some comments to try and help illustrate the broad strokes of how you could go about it.
The only other thing you could do on top of this is put in a test to make sure their browser supports localStorage and then, if it doesn't, you could fall back to trying to use cookies or some other method!
function updateScrollStuff() {
// this tells us how far down we've scrolled as a number, like '476'
var scrollPosition = $(document).scrollTop();
// I cant access localStorage from the iframe they're using here, but I think this
// would be what you'd want to do with it to store that scroll position
// localStorage.storedScrollPosition = scrollPosition;
// this line is just illustrative, showing you that the number for the scroll position is updating
// every time you scroll - you don't need this for your final purposes
$("#scroll-position").text(scrollPosition + "px");
}
// when the user scrolls, call that function above
$(window).scroll(function() {
updateScrollStuff();
});
// I can't test it here, but on page load I would check to
// see if a value exists, and then scroll to it if it does!
$(window).load(function() {
// again, with local storage blocked all I can do is show you what
// it would look like
// typeof 'undefined' is just a check you can make to see if a variable exists
// if (typeof localStorage.storedScrollPosition != 'undefined') {
// $("html, body").scrollTop(localStorage.storedScrollPosition);
// }
});
body, html {
margin: 0;
padding: 0;
}
.section {
width: 100%;
height: 200px;
}
#section-1 {
background-color: #333333;
}
#section-2 {
background-color: #666666;
}
#section-3 {
background-color: #999999;
}
#section-4 {
background-color: #aaaaaa;
}
#scroll-position {
background-color: black;
color: white;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 15px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="section-1" class="section"></div>
<div id="section-2" class="section"></div>
<div id="section-3" class="section"></div>
<div id="section-4" class="section"></div>
<h3 id="scroll-position">Scroll to see this change</h3>

Related

scrollTo() function does nothing

I wanted to scroll to the bottom of the page using vanilla JS, but I encountered a problem. The code below is supposed to scroll to the bottom of the page:
window.scrollTo(0,document.body.scrollHeight);
Whereas all it does is logs "undefined" in the console. Inputting
document.body.scrollHeight
returns an integer 736. Other than that, it doesn't matter what I input into the function's parameters, nothing happens. What more, it only happens on one website. What may matter (not sure) is that the website hides its vertical scrolling bar, even thought it has a really long list of content.
The problem might be that the actuall scroll that you have on the website is not the scroll of the body but a scroll of another element inside that body.
Here is an example:
$('#btn1').click(function() {
window.scrollTo(0,document.body.scrollHeight);
});
$('#btn2').click(function() {
el = $('.a')[0];
el.scrollTop = el.scrollHeight;
});
body {
overflow: hidden;
margin: 0;
padding: 0;
}
div.a {
height: 100vh;
overflow: auto;
}
div.b {
height: 1500px;
position: relative;
}
div.c {
position: absolute;
bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
<div class="b">
<button id="btn1">Scroll body - doesn't work</button><br />
<button id="btn2">Scroll element - will work</button>
<div class="c">This is at bottom of page</div>
</div>
</div>
Note - the usage of jquery is only to make the example shorter.
Put some content in your page o style the body heigth = 1500px for example, then try to execute same code.
Solved. This is what had to be done:
document.getElementsByTagName('body')[0].style.display = "block";
For whatever reason, changing the display to "block" enabled the scrolling using the given code:
window.scrollTo(0,document.body.scrollHeight);
If you will try to type in browser's console like a var a = 5 you also will get undefined. It happens that your example and my did not return anything.

Play animation when content get into view

I've been searching on many posts but almost all of them are confusing.
I'm working with animate.css into a which is at the middle of my page.
For default the animation is played when the page is loaded, but i want that it play when i reach the (when i'm scrolling).
Please, don't say about JS Reveal, i'd like to use the animation from animate.css
What i was trying:
HTML
<!-- Others div above -->
<div class="row sf-medida" id="sf-medida" onscroll="Animar();">
<!-- Others div below -->
JS
function Animar() {
setTimeout(function(){
document.getElementById("sf-medida").style.visibility = "visible";
$("#titulo-general").addClass("animated fadeInLeft");
$(".sub-titulo").addClass("animated bounceInRight");
$(".titulo-izquierda").addClass("animated swing");
$(".texto-1").addClass("animated fadeIn");
$(".texto-2").addClass("animated fadeIn");
},1000)
}
But it doesn't work, however, i've tried adding
window.addEventListener("scroll", Animar);
But what it does is that the animation is played whenever i scroll on the page,
This can be very easily done using little jquery. All you need to do is listen to the scroll event, then check if user have scrolled to the target element. If the user did, then add animation class from your animate.css. Adjust your if condition according to your desires. Check the below code and fiddle https://jsfiddle.net/15z6x5ko/ for reference
$(document).ready(function(){
$(document).scroll(function(evt){
var v2 = Math.abs($('.box').position().top - $(window).height()/2);
var v1 = $(this).scrollTop();
if( v1 > v2 ){
console.log('in');
$('.box').addClass('animated flip')
}
});
});
So as per your request, let me try to explain the code line by line
$(document).ready(function(){
This is easy to understand. It just waits for browser to load all HTML & CSS first and when everything is loaded, the javascript code inside this function will run.
$(document).scroll(function(evt){
This is an event handler, our callback function will run whenever user scrolls on document. Remember change $(document) according whatever the parent is of your target element. So if your target div is inside another div whose class is .parent then use $('.parent').scroll . As for my code I am listening the event on document. When my document scrolls, my event will trigger.
var v1 = $(this).scrollTop();
This code will get the amount of scrolling user had done in pixels.
var v2 = Math.abs($('.box').position().top - $(window).height()/2);
This is a simple math that checks the position of my target div from its parent element subtracting the half of the size of window from it. This will return the pixel positing of your target div. So when user reaches this pixel positing while scrolling, your animation will start.
$('.box').addClass('animated flip')
Now this code simply adds the animation css classes into the target div as soon as user scrolls to the target div.
I'm using "WoW.js" for my scroll reveal library. It's pretty easy to use, like for real. One line of code
<div class="wow fadeIn">content</div>
Here, take a look: http://mynameismatthieu.com/WOW/docs.html
Here's an example using Jquery.
In it we use .scrollTop and .height to measure the videos container from the top of the page so that we know when it comes into view when scrolling. (it's actually set to load when it reaches 100px below the bottom of the viewable area, a sort of preload. you can adjust it to whatever you like.)
The video load is done by copying the url from data-src= into src= when the video container is at the desired spot on the page. (in this case, 100px below the viewable area)
fiddle
note, the video won't load on stack so be sure to view the fiddle
https://jsfiddle.net/Hastig/xszu6b1p/
I scraped it together from these two answers..
Youtube Autoplay
Ladyload Images
$(window).scroll(function() {
$.each($('iframe'), function() {
if ( $(this).attr('data-src') && $(this).offset().top < ($(window).scrollTop() + $(window).height() + 100) ) {
var source = $(this).data('src');
$(this).attr('src', source);
$(this).removeAttr('data-src');
}
})
})
body {
margin: 0;
}
.filler {
display: flex;
justify-content: center;
align-items: center;
height: 800px;
}
.filler-top { background-color: blue }
.filler-btm { background-color: green; }
.video-container {
/* css tricks - responsive iframe video */
/* https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php */
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
height: 0;
display: flex;
justify-content: center;
background-color: red;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filler filler-top">filler top</div>
<div class="video-container">
<iframe data-src="https://www.youtube.com/embed/f0JDs4FY8cQ?rel=0&autoplay=1"></iframe>
</div>
<div class="filler filler-btm">filler bottom</div>

Change iframe style on second load, doesn't work in Internet Explorer 9

I am trying to change the style of an iframe on the second load. I tried this:
$(function() {
var loadCnt = 0;
$('#iframem').load(function() {
if (loadCnt >0) {
$("#idiv").width(453).height(349);
$("#iframem").css("left", "-656px");
$("#iframem").css("top", "-250px");
}
++loadCnt;
});
});
HTML:
<div style="overflow: hidden; width: 377px; height: 230px; position: relative;" id="idiv">
<iframe id="iframem" src="http://www.example.org" style="border: 0pt none ; left: -1px; top: -8px; position: absolute; width: 1680px; height: 867px;" scrolling="no"></iframe></div>
It works perfectly, but it is not working on Internet Explorer 9. What is the correct approach to do that?
I think there is a logical problem in your approach and am not sure how you have it working at all. As JavaScript only runs after the page loads, this mean that in your code you would never actually get to loadCnt larger than 1 - as every time you load the page it sets it to 0 again.
In order to achieve what you are describing you will need to take a different approach, and there are several ways to go about it:
Use a server-side language and use a session variable where you set
the load count
If your pages are loaded through Ajax and injected to the DOM, then, for example, if your code is on the home page on the first 'real'
load of the page the loadCnt and then moving between pages when
you 'load' the homepage again you actally are not loading the whole
JavaScript script, just re-injecting the HTML to the document and then you can add a listener that uses the loadCnt.
Use JavaScript localStorage - on the first load you will set the
counter to 0 on a local storage object that you will be able to
retrieve on later loads:
if (localStorage.getItem("counter") === null) {
// Check if the item exists; if not set it to 0 as it is the first run
localStorage.setItem('counter', 0);
}
else {
// Get the counter - here you can do your work for when the page is loaded after the first load
localStorage.getItem('counter');
}
Use a Javascript cookie to do the same as in previous logic, but in a cookie (as localStorage could have compatibility issues)
You should always use the onload attribute to set any function. In Internet Explorer you can't set the onload event by code. There is the way to do it, I mentioned in option 2 of my answer.
Option 1
HTML
<div style="overflow: hidden; width: 377px; height: 230px; position: relative;" id="idiv">
<iframe id="iframem" src="http://www.example.com" style="border: 0pt none ; left: -1px; top: -8px; position: absolute; width: 1680px; height: 867px;" scrolling="no" onload="myIframeLoadFunction()">
</iframe>
</div>
JavaScript Code
var loadCnt = 0;
function myIframeLoadFunction(){
if (loadCnt >0) {
$("#idiv").width(453).height(349);
$("#iframem").css("left", "-656px");
$("#iframem").css("top", "-250px");
}
++loadCnt;
}
Option 2
You need to specifically bind onload event after element gets render on HTML.
JavaScript Code
(function (selector) {
var loadCnt = 0, frame = $(selector).get(0);
if (frame) {
frame.onload = function () {
if (loadCnt >0) {
$("#idiv").width(453).height(349);
$("#iframem").css("left", "-656px");
$("#iframem").css("top", "-250px");
}
++loadCnt;
};
}
})('#iframem');

How do I make a div (menu) fixed positioned after some scrolling has happened?

I'm making a theme for a website and I was given permission to play with the HTML files. The thing is I'm just familiarised with CSS and HTML, but I'm a complete noob when it comes to Javascript, JQuery, etc. and, sadly, it seems I need those to add some features I want.
I'd like a menu that works like this one: https://www.planetside2.com/news
The HTML is basically this:
<div id="wrap">
<div id="page-header">
<div class="headerbar">
</div>
</div>
And plenty stuff inside, but I hope the containers are enough
This is the CSS:
#wrap {
margin: 0 auto;
width: 1024px;
}
.headerbar {
background: url("{T_THEME_PATH}/images/headerbarbg.png") no-repeat ;
background-position: center;
width: 1054px;
margin:0 -15px;
margin-top:3px;
height: 120px;
position: relative;
padding-top: 70px;
}
I've checked out some other solutions, but, as I said, I'm a complete noob at scripting and when I try to apply such scripts to the theme, they don't work, most likely because there are some things that I should change that I don't know (except classes and IDs, of course).
I hope someone can help me.
First of all you need to detect scrolling and window resize
$(document).ready(function(){
$(window).on("scroll resize", function(e){
var elem = $(".headerbar");
// check if your header is visible by subtracting
// the top offset of your div from the scrolltop distance
if ((elem.offset().top - $(window).scrollTop()) <= 0 && elem.css("position") !== "fixed") {
console.log("not visible");
elem.css({
position:"fixed",
"z-index":"9999",
top:"0px"
});
// check if your header height is greater or equal to the scrolltop distance
} else if (elem.height() >= $(window).scrollTop()) {
console.log("visible");
elem.css({
position:"relative"
});
}
});
})
And here is a simple demo: JSFIDDLE
Some thing i have done previously in fiddle just check this one out will help you to have a scratch.
$(document).ready(function () {
var top_fixed;
if ($('#header-con').length > 0)
{
top_fixed = $('#header-con').offset().top;
}
$(window).scroll(function () {
if ($('#header-con').length > 0)
{
$('#header-con').toggleClass('fixed', $(window).scrollTop() > top_fixed);
}
});
});
DEMO
This short jquery code is what you need.
Tested and was working in a website i had develop lately.
$(window).scroll(function() {
if($(window).scrollTop() != 0) {
$('#fixed-menu-top').css('position', 'fixed').fadeIn();
} else {
$('#fixed-menu-top').css('position', 'absolute').fadeOut();
}
});
Just edit the ids to yours ex #fixed-menu-top to #wrap or any ids in ypur mark up
See website

Displaying news with javascript

I keep coming up against this issue. Displaying news on a website. And I'd like to come up with a solution to use like a template, something I can just drop on a site easily.
The solution I keep seeing is an iframe with javascript to scroll the content. However, I'm really opposed to the idea of using iframes, I think the time for those has passed.
I want to use JS without a framework, because it disallows using other frameworks.
Does anyone know where I could find something robust?
(I'm thinking of using vertical scrolling, but I'm also curious about other solutions)
I found a script that seems to wok well for me, maybe someone else will find this helpful
/***********************************************
* Cross browser Marquee II- © Dynamic Drive (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/
var delayb4scroll=1000; //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1; //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=1; //Pause marquee onMousever (0=no. 1=yes)?
var tim;
////NO NEED TO EDIT BELOW THIS LINE////////////
var copyspeed=marqueespeed;
var pausespeed=(pauseit==0)? copyspeed: 0;
var actualheight='';
function scrollmarquee(){
//document.write(parseInt(cross_marquee.style.top));
//if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8)) {
if (document.getElementById('track').value == "") {
if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8)) {
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px";
//alert(actualheight);
}
else {
//alert(parseInt(marqueeheight));
cross_marquee.style.top=parseInt(marqueeheight)-8+"px";
}
}
}
//on mouse out
function mouse_out() {
clearTimeout(tim);
scrollmarquee;
}
//init()
function initializemarquee(){
cross_marquee=document.getElementById("vmarquee");
cross_marquee.style.top=0;
marqueeheight=document.getElementById("marqueecontainer").offsetHeight;
actualheight=cross_marquee.offsetHeight;
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
cross_marquee.style.height=marqueeheight+"px";
cross_marquee.style.overflow="scroll";
return
}
setTimeout('lefttime=setInterval("scrollmarquee()",55)', delayb4scroll);
}
//event listener
if (window.addEventListener) {
window.addEventListener("load", initializemarquee, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", initializemarquee);
}
else if (document.getElementById) {
window.onload=initializemarquee;
}
the html:
<!-- scroll -->
<div id="marqueecontainer" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed">
<div id="vmarquee" class="vmarquee_content">
<!--YOUR SCROLL CONTENT HERE-->
</div>
</div>
<input id="track" name="track" type="hidden" value="">
and the css:
#marqueecontainer{
position: relative;
width: 250px; /*marquee width */
height: 150px; /*marquee height */
background-color: white;
overflow: hidden;
border: 1px solid #666666;
padding: 2px;
padding-left: 4px;
}
.scroll_div {
border:solid 1px #3366FF;
width: 260px;
width/**/: 280px !important;
}
.vmarquee_content {
position:absolute;
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
}
Why don´t you take a div insert an other div an give the second div a nagative top value.
<script type="text/javascript">
function toTop(top_value)
{
if (top_value == 0)
{ document.getElementById('news').css.top = '0'; }
document.getElementById('news').css.top = '-5px';
}
window.setTimeout('toTop(1)', 100);
window.setTimeout('toTop(0)', 10000);
</script>
This is untested, but I´ve done it this way.

Categories