Waypoints JavaScript(Jquery) - javascript

I am developing a webpage and I wanted to know how to go about making animations based on where the page currently is.
What I mean is that :
for example, the Markup below
<body>
<div id = "header">
<p> header content goes here</p>
</div>
<div id = "content">
<div id = "first">
<p>when I sroll into this region I want the background to darken up(and information appears) and an arrow to appear at the bottom showing prompting to scroll down</p>
</div>
<div id = "second">
<p>when I sroll into this region I want the navbar to to change appearace and display info relative to that div only </p>
</div>
<div id = "third">
<p>when I scroll into this region I want a another effect to occur</p>
</div>
</div>
<div id = "footer">
<p>footer content goes here</p>
</div>
</body>
if the web page loads and I scroll into each of the three divs in the then i want to have a defined effect in action.
How do I do I go about that in JavaScript(Jquery)? or if anyone knows of any good sources where i can learn this technique i will love to know
Thank you all

Something like this should do the trick, either inside the pageLoad or $(document).ready methods:
var last,
docHeight= $(window).height(),
firstTop = $("#first").offset().top,
firstBottom = firstTop - docHeight,
secondTop = $("#second").offset().top,
secondBottom = secondTop - docHeight,
thirdTop = $("#third").offset().top,
thirdBottom = thirdTop - docHeight;
$(document).scroll(function(){
var thisTop = $(this).scrollTop();
if(thisTop <= thirdTop && thisTop >= thirdBottom){//#third is now visible
if(last != 3)//check if we're already in #third
console.log("entered third");//we entered #third for the first time, trigger effect
last = 3;
} else if (thisTop <= secondTop && thisTop >= secondBottom){
if(last != 2)
console.log("entered second");
last = 2;
} else if (thisTop <= firstTop && thisTop >= firstBottom){
if(last != 1)
console.log("entered first");
last = 1
} else
last = 0;
})
It attaches to the $(document).scroll event, and using jquery's scrollTop() for the document, and offset().top of the elements, determines which one has been scrolled to. It also keeps a variable with the last element that was scrolled to, so the console.log statements are only fired when the element is scrolled to originally, thus it won't fire while scrolling through the element.
working jsfiddle

I had a similar issue recently. I found the free and open-source divPeek library to be excellent.
https://github.com/davidhalford/DivPeek
No need to reinvent the wheel, especially if it has already been invented! :)

Related

How to change a div class after scrolling past, and then change it back to original when completing the same scrolling action for a second time?

In my html I've got a div that changes its class when the user scrolls past it (and the div becomes out of view), such that when the user scrolls back up the page the class is changed.
I would like to have that div class reverted to original the second time the user scrolls back up, but just can't figure out a way to do so. I'm trying to find a way for it to work in such a way that the effect repeats and the class alternates every time it comes back into view.
I'm doing this with two scripts at the moment. The first one works and changes the class of the div when the user scrolls back up:
<script>
$(function() {
var scroll1 = $(window).scrollTop(); // how many pixels have been scrolled
var os1 = $('#div1').offset().top; // pixels to top of div1
var ht1 = $('#div1').height(); // height of div1 in pixels
if (scroll > os1 + ht1) {
$('#div1').removeClass('english').addClass('japanese');
}
});
</script>
But the second one doesn't seem to do anything at all:
<script>
$(function() {
var scroll2 = $(window).scrollTop();
var os2 = $('#div1').offset().top;
var ht2 = $('#div1').height();
var class1 = document.getElementsByClassName('japanese')[0].className;
if (scroll > os1 + ht1 && class1 == 'japanese') {
$('#div1').removeClass('japanese').addClass('english');
}
});
</script>
I guess this is happening because you have the same conditions in both of the functions.
For the second condition use this instead
if(scroll < os1 + ht1)

How to know what part of HTML is the user on

so I want to know how I can get what section or part of my html I’m currently on. An example
So how do I know if a user has already scrolled down over part 2 using JavaScript
Or if they’re currently at part 1
<html>
<head>
</head>
<body>
<section class=“part 1”>
</section>
<section class= “part2>
</section>
</body>
</html>
The following codes will give you a little idea about how to handle this situation. Essentially you are going to want to get the scrollbar position which you can do using:
document.documentElement.scrollTop
You also want to get a range where the element you are looking for resides, in our case, it is .part1 and .part2. We can get that range by using offsetTop as the beginning of the limit and offsetTop + clientHeight to determine the end.
You are going to have to keep track of the window scroll event.
The following example is generic:
$(window).scroll(function(e) {
if (document.documentElement.scrollTop > 0
&& document.documentElement.scrollTop < $('.part2').offset().top ) {
$('div').html("At part1")
} else {
$('div').html("At part2")
}
});
JSFiddle
Likewise, if you want a little bit of modularity:
$(window).scroll(function(e) {
let watchList = ['part1', 'part2', 'part3'];
let scrollTop = document.documentElement.scrollTop;
for (var classname of watchList) {
let el = document.getElementsByClassName(classname)[0];
if (scrollTop > el.offsetTop &&
scrollTop < el.offsetTop + el.clientHeight) {
$('div').html("At <strong>"+classname+"</strong>");
}
}
});
JSFiddle
The possibilities are limitless to continue and make this more useful, but I'll leave that up to you.
you can use is[":focus"] function to find which div has focus currently.
if($(".part1").is(":focus"))
{
//you code
}
else if($(".part2").is(":focus"))
{
//you code
}
you can use mouseenter function it fires when the mouse goes into that div for the first time.
$(".part1").on('mouseenter', function(){
//your command
});
you can use mouseover function to find where is mouse right now. it fires when mouse moves inside that div.
$(".part1").on('mouseover', function(){
//your command
});
You can use javascripts offsetTop functionality. This is a parameter that returns how far down from the top a div is in the number of pixels.
It can also return how far down the user has scrolled when called on the window object itself. Then it's just a matter of math. See if the user has scolled down far enough to be past the div in reference.
For example:
var part1DivOffset = document.getElementsByClassName("part 1")[0].offsetTop;
var part2DivOffset = document.getElementsByClassName("part2")[0].offsetTop;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
This code will get you 3 variables. The first 2 lines save the offsetTop of the div's. While the third line detects how far down the user has scrolled. Then you can do math with the variables:
if(scrollTop >= part1DivOffset){
//we are past part1
}
if(scrollTop >= part2DivOffset){
//We are past part 2
}
if(scrollTop >= part1DivOffset && scrollTop < part2DivOffset){
//We are past part 1 but not past part 2
}

How to detect if an element is outside of its container's width?

How can I detect an element that is completely (not partially) outside of a specific containers width?
For example, I have the following:
<div id="content">
<div class="wrapper">
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</div>
</div>
My content div has the width of 100%, and my p tags are animated to scroll across the screen. How can I detect if they are outside of the content div so that I can remove them?
Testing for outside of the viewport is not an option since my content div also has a container.
I believe the getBoundingClientRect() method should work well. Made a better working example using the paragraphs, here's the fiddle.
function HorizontallyBound(parentDiv, childDiv) {
var parentRect = parentDiv.getBoundingClientRect();
var childRect = childDiv.getBoundingClientRect();
return parentRect.left >= childRect.right || parentRect.right <= childRect.left;
}
var bound = HorizontallyBound(document.getElementById("parent"), document.getElementById("some_paragraph"));
Or using jQuery with the same concept:
function HorizontallyBound($parentDiv, $childDiv) {
var parentRect = $parentDiv[0].getBoundingClientRect();
var childRect = $childDiv[0].getBoundingClientRect();
return parentRect.left >= childRect.right || parentRect.right <= childRect.left;
}
var bound = HorizontallyBound($("#parent"), $("#some_paragraph"));
Updated my answer because I reread that you're checking if the child is completely outside of the parent, not partially.
If I understand what you're asking correctly, you could try something I use on one of my own sites:
var $elem = $('#preview_link_box'),
top = $elem.offset().top,
left = $elem.offset().left,
width = $elem.width(),
height = $elem.height();
if (left + width > $(window).width()) {
console.log("Looks like its outside the viewport...");
}
I don't know what you're trying to do, but I tried to create something similar. It's a really simple idea as far as the logic. jsfiddle here
Basically the idea was to use the width of #content div and slide the p elements over until it reached that number and then remove them.
var width = $('.wrapper p:first').width(),
i = 0,
$me = $('.wrapper p');
// slide paragraphs over to the left, once out of bounds they are removed
var interval = setInterval(function() {
if (i == -width) {
clearInterval(interval);
$me.remove();
}
$me.css('margin-left', --i);
}, 10);

Auto Scroll To A each div or element

I need some help regarding auto scroll to each div or element when the user will use the scroll button in the mouse. Here goes the scenario
Suppose this is my structure of the page..
<div id="main-wrap">
<div class="my-div-1">
<p>here goes my content 1</p>
<img src="/images/sample-1" alt="sample-1"/>
</div>
<div class="my-div-2">
<p>here goes my content 2</p>
<img src="/images/sample-2" alt="sample-2"/>
</div>
<div class="my-div-3">
<p>here goes my content 3</p>
<img src="/images/sample-3" alt="sample-3"/>
</div>
</div><!-- end of main-wrap id -->
-Now suppose my each div has got enough content to make the page long. Suppose the user is on my-div-1 and when the viewer uses the scroll button to scroll down, instead of scrolling through the whole div, i want it to scroll automatically to the my-div-2.
I hope my explanation make sense here.
Is there any way to sort it out by using javascript and jquery?
I will appreciate any response..Thanks in advance.
Here's a fiddle with what you want: http://jsfiddle.net/3qxhY/9/
Source of plugin used in code (debounce/throttle plugin): http://benalman.com/projects/jquery-throttle-debounce-plugin/
Code
// debounce/throttle plugin
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);
//elements you want to scroll to go here
divs = [$(".my-div-1"),$(".my-div-2"),$(".my-div-3")];
var lastScrollTop = 0; //we'll update this on every scroll and compare it to the last scroll to determine the scroll direction
var run = true;
$(window).scroll($.debounce(250, true, function () { //debounce so it only runs once per scroll
var st = $(window).scrollTop();
if (st > lastScrollTop) { // if the scrollTop when the scroll event fires is larger than the last scroll, we can assume the scroll was in a downward direction
$.each(divs, function (i, v) {
((v.offset().top - $(window).scrollTop()) < 0) && (next = i + 1); //compare each elements offset to the windows offset to determine which element we're currently scrolling through
});
run = (next != divs.length) ? true : false; //dont run if we are at the last div
} else {
$.each(divs, function (i, v) {
((v.offset().top - $(window).scrollTop()) < 0) && (next = i);
});
run = true;
}
if (run) {
$('html, body').animate({
scrollTop: divs[next].offset().top
}, 1000,'linear', function() {
lastScrollTop = $(window).scrollTop();
});
} else { lastScrollTop = $(window).scrollTop(); }
}));

Random banner positioning on website's page. Possible?

Can someone tell me how I can achieve the following?
I want to display a banner on my website's page (of course this is easy). However I want it to appear randomly (a single time) in one of the 4 positions I selected (DIV ID's bannerpos1, bannerpos2, bannerpos3 and bannerpos4).
If the banner shows up in bannerpos2, it shouldn't appear at any other location and vice versa.
And, only if possible, it should display a random banner as well (choice out of 3 banners or so).
So in short; I want a random banner in a random position on my page. Of course the banners and positions are yet to be defined.
Can someone help me, or point me in the right direction?
//update 7th of November
Okay, I have been fooling around with the script as show by Joe, however I am experiencing some problems...
Currently the code looks like this (before body-tage):
<script type="text/javascript">
$(function(){
var position = Math.floor((Math.random()*3));
console.log(position)
var $a = $("#advertentieplaats1");
var $b = $("#advertentieplaats2");
var $c = $("#advertentieplaats3");
var $advertentietype1 = $("#advinhoud1");
var $advertentietype2 = $("#advinhoud2");
var $advertentietype3 = $("#advinhoud3");
if (position == 0){
$a.append($advertentietype1);
}
if (position == 1){
$b.append($advertentietype2);
}
if (position == 2){
$c.append($advertentietype3);
}
});
</script>
And at the bottom of the page I have the following:
<div id="advinhoud1">adsense code 1</div>
<div id="advinhoud2">adsense code 2</div>
<div id="advinhoud3">adsense code 3</div>
Or there are some problems with this, or I am doing it wrong somehow...
In Firefox it shows the adsense code on random (defined) locations. It also shows the remaining 2 advertisements at the bottom (which should not be visible or even loaded).
In Internet Explorer it doesn't do anything at all...? All Adsense is shown at the bottom, nothing in random locations...?
Something like this. You can make it more dynamic, but here's the idea.
var position = Math.floor((Math.random()*3));
var $a = $("#myDiv1"); // Get the three containers as JQuery objects by id.
var $b = $("#myDiv1");
var $c = $("#myDiv1");
var $myAd = $("#myAd"); // Get the content you want to place.
// You could include it as a string in your JS
// or as a hidden element.
if (position == 0)
{
$a.append($myAd);
}
if (position == 1)
{
$b.append($myAd);
}
if (position == 2)
{
$c.append($myAd);
}

Categories