jquery else condition inside onscroll function - javascript

I have a problem in animation in onscroll event.
The if condition works very well when I scroll down and div shows without any problem, but when I scroll up, the else condition does not work, so the div doesn't hide and it is still shown.
This is the code:
$(function () {
'use strict';
var myDiv1 = $('div'),
div1Top = (myDiv1.offset().top) / 2;
$(window).on('scroll', function () {
var docScrollTop = document.documentElement.scrollTop;
if (docScrollTop >= div1Top) {
$('div').animate({opacity: '1'}, 800);
} else {
$('div').css('opacity', '0');
}
});
});

This might not be exactly what you're trying to do, but I think it's in the right ballpark:
<html>
<style>
div {
width: 500px;
height: 500px;
}
.animated_div {
background-color: green;
position: absolute;
top: 2000px;
opacity: 0;
}
.placeholder {
position: absolute;
top:4000px;
}
</style>
<body>
<div class="animated_div"></div> <!--The div that will actually be animated-->
<div class="placeholder"></div> <!--This is just something below the animated DIV, so that you can scroll below the animated DIV -->
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
'use strict';
var myDiv1 = $('.animated_div');
// Start animating the div relative to its middle
var div1Middle = myDiv1.offset().top + myDiv1.height() / 2;
// Keep track of whether the animated_div is displayed or not
var myDiv1Shown = false;
$(window).on('scroll', function () {
var docScrollTop = $(window).scrollTop(); // Top of the window in page coordinates
var docScrollBottom = docScrollTop+$(window).height(); // Bottom of the window in page coordinates
if (div1Middle > docScrollTop && div1Middle < docScrollBottom && !myDiv1Shown) {
// The div middle is within view and it's not already shown, so we need to show it
myDiv1Shown = true;
myDiv1.animate({opacity: '1'}, 800);
} else if ((div1Middle > docScrollBottom || div1Middle < docScrollTop) && myDiv1Shown) {
// The div middle is out of view and it's shown, so we need to hide it
myDiv1Shown = false;
myDiv1.animate({opacity: '0'}, 800);
}
});
});
</script>
</html>
This changes the div opacity to 1 when it's in view and changes it to 0 when it's out of view. It's considered in-view if its vertical middle is in view.
If what you want to do is essentially fade-in the div when the user scrolls it into view and then fade-out the div when the user scrolls it out of view, you might consider this as an alternative:
<html>
<style>
div {
width: 500px;
height: 500px;
}
.animated_div {
background-color: green;
position: absolute;
top: 2000px;
opacity: 0;
}
.placeholder {
position: absolute;
top:4000px;
}
</style>
<body>
<div class="animated_div"></div> <!--The div that will actually be animated-->
<div class="placeholder"></div> <!--This is just something below the animated DIV, so that you can scroll below the animated DIV -->
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
'use strict';
var myDiv1 = $('.animated_div');
var div1Top = myDiv1.offset().top;
var div1Height = myDiv1.height();
var div1Bottom = div1Top + div1Height;
$(window).on('scroll', function () {
var docScrollTop = $(window).scrollTop(); // Top of the window in page coordinates
var docScrollBottom = docScrollTop+$(window).height(); // Bottom of the window in page coordinates
// Calculate fraction of div on page
var topOffPage = Math.max(0, docScrollTop - div1Top);
var bottomOffPage = Math.max(0, div1Bottom - docScrollBottom);
var fractionOnPage = Math.max(0, div1Height - topOffPage - bottomOffPage)/div1Height;
myDiv1.css('opacity', fractionOnPage);
});
});
</script>
</html>
The snippet immediately above sets the opacity of the div to be the fraction of it that is in view (considering only the vertical dimension). So if the entire DIV is on-screen, it's fully opaque. If only half of it is onscreen (with half of it either above the scroll top or below the scroll bottom), then the opacity is 0.5, and so on. If the div is large relative to the screen, then this could cause problems. For instance, if you have a 1000px div, and people are viewing the page with a viewport of height 500px, then the div will only ever be 50% opaque at most. But you can adapt it as necessary to fit your circumstances.

Related

How to hide a header nav when scrolling, and show when scrolling has stopped

I have a navigation header (normal HTML header tag).
I want to fade it out when a user scrolls down, but show it when the user stops scrolling (after a 1 second delay).
How can I achieve this with using jQuery? This is what I have got so far:
jQuery(function($){
var lastScrollTop = 0, delta = 15;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if(Math.abs(lastScrollTop - st) <= delta)
return;
if ((st > lastScrollTop) && (lastScrollTop>0)) {
// downscroll code
$("header").css("top","-80px");
} else {
// upscroll code
$("header").css("top","32px");
}
lastScrollTop = st;
});
});
This might help you, try to implement this example in your code:
In this example, we are setting up the scroll event, so every time user perform the scroll operation following action is taken:
Fade out the header.
Clear the Time out, if it is set in the t var.
Set the timeout for 1 second, action taken after this timeout is to fade in the header again.
So, every time if one scroll point moved, event get called, header fade out and we setting a timout to display header after 1 second, but before that if another scroll point move, event again get called. and previous timer get cleared.
This goes on n on until, user stop scrolling and then last time out function execute successfully and fade in the header again.
$(function(){
var t;
document.addEventListener('scroll',function(e){
$("#Header").fadeOut(500);
clearTimeout(t);
checkScroll();
});
function checkScroll(){
t = setTimeout(function(){
$("#Header").fadeIn(500);
},1000); /* You can increase or reduse timer */
}
});
html, body { height: 1200px; margin: 0; padding: 0; width: 100%; }
#Header { background: red; height: 100px; left: 0; position: fixed; top: 0; width: 100%; }
#Header table { height: 100%; width: 100%; }
#Body { background: grey; height: 200%; margin-top: 100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="Header">
<table>
<tr>
<th>H E A D E R bar</th>
</tr>
</table>
</div>
<div id="Body">
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</div>
In your code, rather than using fading effect, position of header is changed, so when the position of the header is change to hide it, set the timer to bring it back, in this way you show the header when scrolling stops.
$(function(){
var lastScrollTop = 0, delta = 15;
var t;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if(Math.abs(lastScrollTop - st) <= delta)
return;
if ((st > lastScrollTop) && (lastScrollTop>0)) {
// downscroll code
$("header").css("top","-80px");
clearTimeout(t);
checkScroll();
}
lastScrollTop = st;
});
function checkScroll(){
t = setTimeout(function(){
$("header").css("top","0px");
},1000); /* You can increase or reduse timer */
}
});
I ended up with the following code:
jQuery(function($){
var lastScrollTop = 0, delta = 15;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if(Math.abs(lastScrollTop - st) <= delta)
return;
if ((st > lastScrollTop) && (lastScrollTop>0)) {
// downscroll code
$("header").css("top","-80px");
} else {
// upscroll code
$("header").css("top","32px");
}
lastScrollTop = st;
});
});
Codepen: https://codepen.io/Canvasandcode/pen/bGGeWrj

Javascript countdown and redirect - Part 2

I have a webpage that runs a JavaScript modal popup box with a message in it informing the visitor that they will be redirected to our new site in XX seconds. It also has two links saying "Agree" (then they are redirected) and "Disagree" (to stay on the old/current website).
This all seems to work fine but what I want it to do is stop the redirect when the user either clicks the Disagree link and/or when they click the darkened area outside the popup box (called #mask).
How can I get this to work? - the JS code is below.
Here is the popup box JS code:
$(document).ready(function() {
var id = '#dialog';
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(500);
$('#mask').fadeTo("slow",0.9);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
//if Disagree word is clicked
$('#disagree').click(function () {
$(this).hide();
$('.window').hide();
$('#mask').hide();
});
//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
});
And here is the countdown timer code (which is not external like the above popup.js but in the page itself):
<script src="popup.js"></script>
var time_left = 12;
var cinterval;
function time_dec(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 1){
var originalstring = document.getElementById('countdown2').innerHTML;
var newstring = originalstring.replace('seconds','second');
document.getElementById('countdown2').innerHTML = newstring;
window.location.replace("http://cadfemukandireland.com/");
clearInterval(cinterval);
}
}
cinterval = setInterval('time_dec()', 1000);
The HTML code is:
<div id="boxes">
<div id="dialog" class="window">
<p>We are currently in the process of upgrading our current website to a new and improved version.</p>
<p>You will automatically be directed to the new website <span id="countdown2">in <span id="countdown">12</span> seconds</span>.</p>
<div id="popupfoot"> I disagree </div>
</div>
<div id="mask"></div>
</div>
Try the code below - It basically zeros the time left when disagree is clicked
I've also assigned the time_dec function to a variable for easier scoping
$(document).ready(function() {
var id = '#dialog';
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(500);
$('#mask').fadeTo("slow",0.9);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
//if Disagree word is clicked
$('#disagree').click(function () {
$(this).hide();
$('.window').hide();
$('#mask').hide();
time_left = 0;
});
//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
});
var time_left = 3;
var cinterval;
document.getElementById('countdown').innerHTML = time_left;
var time_dec = function(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 1){
var originalstring = document.getElementById('countdown2').innerHTML;
var newstring = originalstring.replace('seconds','second');
document.getElementById('countdown2').innerHTML = newstring;
window.location.replace("http://cadfemukandireland.com/");
clearInterval(cinterval);
}
}
cinterval = setInterval(time_dec, 1000);
#dialog {
position: absolute;
width: 300px;
height: 220px;
border: 1px solid #ccc;
padding: 16px;
top: 100px;
left: 100px;
z-index: 999;
background: #fff;
}
#mask {
z-index: 9;
background: rgba(0,0,0,0.6)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boxes">
<div id="dialog" class="window">
<p>We are currently in the process of upgrading our current website to a new and improved version.</p>
<p>You will automatically be directed to the new website <span id="countdown2">in <span id="countdown">12</span> seconds</span>.</p>
<div id="popupfoot"> I agree | <a id="disagree" style="color:red;">I disagree</a>
</div>
</div>
<div id="mask"></div>
</div>

jQuery and getting scroll position only on every 200 scroll

I am trying to get the scroll down and up position at This Demo but as you can see it is updating the <p> element on every single pixel by pixel scroll (Up or Down). But what I need to only update the <p> on every 200 scroll until reaching the end of the div (right now the p element is updating on every single scroll).
Here is the code I have:
$(window).scroll(function () {
var height = $(window).scrollTop();
if (height > 200) {
$('p').html(height);
}
});
div {
height:1080px;
}
p {
position:fixed;
top:0;
left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<p></p>
<div>
<h3> Hello Scroll!</h3>
</div>
How can I fix this?
var a=0;
$(window).scroll(function () {
var height = $(window).scrollTop();
if (height-a<200){
if (height-a<-200){
$('p').html(a);
a = parseInt(height/100) *100;
}
}else{
$('p').html(a);
a = parseInt(height/100)*100;
}
});
div {
height:1080px;
}
p {
position:fixed;
top:0;
left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<p></p>
<div>
<h3> Hello Scroll!</h3>
</div>

Scroll the page vertically and scroll big image inside div horizontally on mouse drag with jQuery

I have page that I want to scroll vertically on event mouse down, and I already have found the answer on this question link. In my case i have a div that contain image that user put on it and sometimes it have bigger size than my div size, with overflow:auto; i get horizontal scroll inside that div. So i need to apply drag scroll horizontally on that div.
HTML
<html>
<body>
<div id="container">
<div class="detail-title"> TITLE </div>
<div class="detail-content">
<img src="...." />
!-- long content --!
</div>
</div>
</body>
</html>
CSS
.detail-main-content-box {
background: none;
display: block;
left: 0;
min-height: 350px;
overflow: auto;
padding: 5px 5px 5px 5px;
width: auto;
}
jQuery from answer link
$(document).on({
'mousemove': function (e) {
clicked && updateScrollPos(e);
},
'mousedown': function (e) {
clicked = true;
clickY = e.pageY;
$('html').addClass('block-selection').css({ 'cursor': 'url(../img/closedhand.cur), default' });
},
'mouseup': function () {
clicked = false;
$('html').removeClass('block-selection').css('cursor', 'auto');
}
});
var updateScrollPos = function(e) {
$(window).scrollTop($(window).scrollTop() + (clickY - e.pageY));
};
how can i apply this on div? i have try to change $(document) to $('.detail-content') also change function scrollTop to scrollLeft but nothing happen. Here is the fiddle for current condition.
this has been left here unanswered for two long years, not even a useful comment. OK, here is my try. hope it can help ( le roi est mort vive le roi)
<script type="text/javascript">
var clicked = true;
var clickY = e.pageY;
$('.detail-content').on({
'mousemove': function (e) {
clicked && updateScrollPos(this,e);
},
'mousedown': function (e) {
clicked = true;
clickY = e.pageY;
$('html').addClass('block-selection').css({ 'cursor': 'grabbing' });
},
'mouseup': function () {
clicked = false;
$('html').removeClass('block-selection').css('cursor', 'auto');
}
});
var updateScrollPos = function(obj,e) {
$(obj).scrollTop($(obj).scrollTop() + (clickY - e.pageY));
clickY = e.pageY;
};
</script>

jQuery function that returns when a div touches another div upon scroll

how can I give an alert when one div hovers over another div upon scroll? here is a working example,
http://jsfiddle.net/uprosoft/Ek5Gy/267/
I cant find a jQuery code to go after though in-order to give an alert.
Code:
HTML
<div id="container">
<div id="div1">test</div>
<br>
<div id="div2"> another test</div>
</div>
CSS
#div1{
background: green;
position: fixed;
width: 100%;
}
#div2{
background: yellow;
position: relative;
width: 100%;
margin-top: 100px;
}
#container{
height: 1000px;
}
JQUERY ???
/* what jquery code goes here? to alert when the yellow div touches the green div upon scroll? */
Something like that should work:
$(window).scroll(function() {
var div1 = $("#div1");
var div2 = $("#div2");
var div1_top = div1.offset().top;
var div2_top = div2.offset().top;
var div1_bottom = div1_top + div1.height();
var div2_bottom = div2_top + div2.height();
if (div1_bottom >= div2_top && div1_top < div2_bottom) {
// overlapped
}
});​
DEMO: http://jsfiddle.net/Ek5Gy/280/
I know the question is for Jquery but either way, the same done with vanilla JS
function didDiv1TouchedDiv2() {
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
// Guard
if (div1 === undefined || div2 === undefined) return;
var div1Rect = div1.getBoundingClientRect();
var div2Rect = div2.getBoundingClientRect();
// We need to add the offsetHeight in order to include padding and border of element and get excact position
return div1Rect.top >= div2Rect.top + div2.offsetHeight;
}
window.addEventListener("scroll", didDiv1TouchedDiv2);

Categories