Let's say I have a single HTML page. 2000 pixels long for example. I want to detect if a visitor reaches a certain point on the page.
The page structure:
- 0px = begin of the page;
- 500px = about us page;
- 1000px = contactpage;
Is there a way with jQuery to detect if a user reaches the points described above?
Let's say I have a single HTML page. 2000 pixels long for example. I want to detect if a visitor reaches a certain point on the page.
The page structure:
- 0px = begin of the page;
- 500px = about us page;
- 1000px = contactpage;
Is there a way with jQuery to detect if a user reaches the points described above?
Share Improve this question asked Dec 3, 2011 at 18:17 Citizen SPCitizen SP 1,4117 gold badges38 silver badges70 bronze badges 1- 1 Check my answer below. You can detect if the element is currently visible when scrolling even without knowing its position. – kubetz Commented Dec 3, 2011 at 18:45
3 Answers
Reset to default 4You probably want jQuery's scroll
event-binding function.
Yes, I would create three divs and then have a mouse over event on each. Example:
$("#begin").mouseover(function(){
alert("over begin");
});
$("#about").mouseover(function(){
alert("over about");
});
$("#contact").mouseover(function(){
alert("over contact");
});
You can see a working fiddle here: http://jsfiddle/ezj9F/
Try THIS working snippet.
Using this code you don't have to know position of the element you want to check if it is visible.
JQuery
var $window = $(window);
// # of pixels from the top of the document to the top of div.content
var contentTop = $("div.content").offset().top;
// content is visible when it is on the bottom of the window and not at the top
var contentStart = contentTop - $window.height();
// content is still visible if any part of his height is visible
var contentEnd = contentTop + $("div.content").height();
$window.scroll(function() {
var scrollTop = $window.scrollTop();
if(scrollTop > contentStart && scrollTop < contentEnd) {
console.log('You can see "HELLO"!');
} else {
console.log('You cannot see "HELLO"!');
}
});
HTML
<div class="scroll"></div>
<div class="content">HELLO</div>
<div class="scroll"></div>
CSS
div.scroll {
background-color: #eee;
width: 100px;
height: 1000px;
}
div.content {
background-color: #bada55;
width: 100px;
height: 200px;
}
EDIT: Now the algorithm is checking if any part of the div.content
is visible (it is considering height of the element). If you are not interested in that change contentEnd
to var contentEnd = contentTop
.