I am trying to detect when a div is at the top of the page with Jquery/Javascript. Anyone any idea's where I might start?
You can listen to the scroll event using jQuery, and every time it changes, get the offset value of the div and compare it with 0.
I would use a function like this:
function elementAtViewportTop(elem) {
if(!elem || typeof elem !== "object") return false;
if(elem instanceof jQuery) elem = elem[0];
var elemClientRect = elem.getBoundingClientRect();
return (elemClientRect.top <= 0 && elemClientRect.top > -(elemClientRect.height));
}
elem.getBoundingClientRect().top will be zero if the element reaches the top of the window (getBoundingClientRect()).
When you add an event listener for scroll to the window and call that function every time on your element, it will work fine:
Demo
Related
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
}
I use anime-js for create an animation. But, It is far in the page. I would like to launch my animation function when the section in which the item to be animated appears on the screen.
I tried a plugin that I like to use (jquery viewportchecker) but it does not seem to do that.
Can you help me ?
Thank you
I found a solution. The problem with your method is that the function repeats itself to infinity.
I create a little function for check if element is visible. With that, no plugin needed.
function checkVisible( elm, evale ) {
var evale;
evale = evale || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
scrolltop = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evale == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (evale == "above") return ((y < (viewportHeight + scrolltop)));
}
I also created a variable var counter = 0;. And as soon as the function is called, I increment by 1.
$(window).on('scroll',function() {
if (counter == 0){
if (checkVisible($('.frontend'))) {
// Your function here
}
}
}
At the first time the function will be called, counter will be 1, and thus, the function will not repeat. Thank you for your help !
jQuery.appear
This plugin implements custom appear/disappear events which are fired when an element became visible/invisible in the browser viewport.
https://github.com/morr/jquery.appear
$('someselector').on('appear', function(event, $all_appeared_elements) {
// this element is now inside browser viewport
});
$('someselector').on('disappear', function(event, $all_disappeared_elements) {
// this element is now outside browser viewport
});
Also this plugin provides custom jQuery filter for manual checking element appearance.
$('someselector').is(':appeared')
Have you tried using JQuery's on load method?
Something like
$(document).on('load', '.exampleClass', function() { //do stuff } )
i have very strange requirement like there are two browser window .
i want to close second window when i dragged this window on first window.
first Is this possible ?
Second If yes then On which event ?
So i can do my desire work at that event.
Right now i have written this code
$(document).on('mouseover', function () {
console.log('done');
});
SO i can get this event when i dargged another window on first window but this event also not happening because at the drag time dragged window active, this window is not active.
Any help is appreciated.
Thanks
You have to check both windows' dimension and position. The snippet below will not work here as StackOverflow blocks pop up windows, so try it somewhere else.
var a;
var b;
function openA(){
a = window.open("","w1","width=250,height=150,top=0");
a.document.title = "A";
}
function openB(){
b = window.open("","w2","width=250,height=150,top=200,left=400");
b.document.title = "B";
}
setInterval(function(){
// If both window is not closed
if (a && !a.closed && b && !b.closed){
// If both window overlaps
if (
a.screenX + a.outerWidth > b.screenX &&
a.screenX < b.screenX + b.outerWidth &&
a.screenY + a.outerHeight > b.screenY &&
a.screenY < b.screenY + b.outerWidth
){
b.close();
}
}
},1000);
<button onclick="openA()">Open window A</button>
<button onclick="openB()">Open window B</button>
As you have not shared any code about child windows and as per comments i can suggest you this:
var cwin = window.open() creates a child window.
Now you can use to get the X position of your window.
You can use setInterval() to check the position of that window.
Then you can check if the X position is in between the width of parent window.
Here you can trigger $(cwin.parent.document).trigger('mouseover') close it by cwin.close();
I recently got aware of a bug in the OSM map:
the map click event seems to trigger at the wrong coordinates if the map div is moved. how would i workaround this problem? i can't guarantee the map div to be fixed, because the site's content may change while the map is shown.
As far as i searched google and stack overflow, i seem to be the only one experiencing that problem...
Here's a fiddle: http://jsfiddle.net/W3f6L/
(set a pointer => click "clickme" => try to set a pointer again)
even the simple setup of the fiddle
<div id="clickme">clickme</div>
<div id="mapdiv"></div>
with js
$("#clickme").click(function(){
$(this).css("height","200px");
});
will reproduce the error.
also pretty odd is, that if you click the clickme and then use the scrollbar to move down, the error vanishes (tough that only happens in the fiddle, i already tried to reproduce this behaviour in the site...)
[EDIT] solution,a bit more generalized than unknown's answer, but based on it....in case someone else stumbles upon a similar problem:
setInterval(function(){
//map container jQuery object...
var o = jQuery(map.div);
if(lastPos == null) lastPos = o.position(); //initally set values
if(lastOff == null) lastOff = o.offset();
//body or whatever div is scrollable, containing the map div
if(lastScroll == null) lastScroll = jQuery("body").scrollTop();
var newPos = o.position(); //getting values at this time
var newOff = o.position();
var newScroll = jQuery("body").scrollTop();
if(lastPos.top != newPos.top ||
lastPos.left != newPos.left ||
lastOff.top != newOff.top ||
lastOff.left != newOff.left ||
lastScroll != newScroll){
//if one of the values has changed, the map needs to be updated
map.updateSize();
}
//reset values for next run
lastPos = newPos;
lastOff = newOff;
lastScroll = newScroll;
},200); //the smaller, the more computing, the bigger the more delay between changes and the map update
You need to update map size using an API updateSize. Try this:
$("#clickme").click(function(){
$(this).css("height","200px");
map.updateSize();
});
DEMO
Is there a way to get elements which is:
Inside a div with overflow: scroll
Is in viewport
Just like the following picture, where active div (5,6,7,8,9) is orange, and the others is green (1-4 and >10) :
I just want the mousewheel event to add "active" class to div 5,6,7,8,9 (currently in viewport). View my JSFiddle
$('.wrapper').bind('mousewheel', function (e) {
//addClass 'active' here
});
You could do something like this. I would have re-factored it, but only to show the concept.
Firstly I would attach this to scroll event and not mousewheel. There are those among us that likes to use keyboard for scrolling, and you also have the case of dragging the scrollbar. ;) You also have the case of touch devices.
Note that with this I have set overflow:auto; on wrapper, thus no bottom scroll-bar.
With bottom scrollbar you would either have to live with it becoming tagged as in-view a tad to early, or tumble into the world of doing a cross-browser calculating of IE's clientHeight. But the code should hopefully be OK as a starter.
»»Fiddle««
function isView(wrp, elm)
{
var wrpH = $(wrp).height(),
elmH = $(elm).height(),
elmT = $(elm).offset().top;
return elmT >= 0 &&
elmT + elmH < wrpH;
}
$('.wrapper').bind('scroll', function (e) {
$('div.box').each(function(i, e) {
if (isView(".wrapper", this)) {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
Note that you should likely refactor in such a way that .wrapper height is only retrieved once per invocation, or if it is static, at page load etc.
Update; a modified version of isView(). Taking position of container into account. This time looking at dolphins in the pool.
»»Fiddle««
function isView(pool, dolphin) {
var poolT = pool.offset().top,
poolH = pool.height(),
dolpH = dolphin.height(),
dolpT = dolphin.offset().top - poolT;
return dolpT >= 0 && dolpT + dolpH <= poolH;
}