I want to trigger a function when the user is on a section of the page with a specific ID (either through a link or scroll). This is what I have now but it's not working.
$(document).ready(function() {
if (window.location.pathname == '/index.html#contact') {
console.log('Viewing contact form');
}
});
UPDATE: Found what I was looking for. This is what I used:
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#contact').offset().top - 50) {
$('.modal').modal('hide');
}
});
The "- 50" is to account for my margins and paddings. When using the subtract symbol it 'assumes' your section starts higher on your page. For lower, use addition.
The "$('.modal').modal('hide');" is not needed. This is to hide a bootstrap modal when the user is on the #contact section of the page.
I want to trigger a function when the user is on a section of the page with a specific ID (either through a link or scroll). This is what I have now but it's not working.
$(document).ready(function() {
if (window.location.pathname == '/index.html#contact') {
console.log('Viewing contact form');
}
});
UPDATE: Found what I was looking for. This is what I used:
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#contact').offset().top - 50) {
$('.modal').modal('hide');
}
});
The "- 50" is to account for my margins and paddings. When using the subtract symbol it 'assumes' your section starts higher on your page. For lower, use addition.
The "$('.modal').modal('hide');" is not needed. This is to hide a bootstrap modal when the user is on the #contact section of the page.
- duplicate of stackoverflow./questions/6271237/… – Katya Pavlenko Commented May 10, 2015 at 16:13
- @Katerina: no, it doesn't seem to be. That question asks how to know when the user has scrolled to the bottom of a given element, whereas this question wants to know - so far as I can tell - when a given element is visible on the page, and how to log, or otherwise act upon, that information. – David Thomas Commented May 10, 2015 at 16:17
- it's the same, look: if user sees the element, he has scrolled to it) the only difference – you should check this on pageload before user first scrolled – Katya Pavlenko Commented May 10, 2015 at 16:23
2 Answers
Reset to default 3The window.location
property in Javascript returns a location object. If you want to match a specific anchor link you need to use the hash
property of the location object. Here's a list of all properties of location objects: http://www.w3schools./jsref/obj_location.asp.
You could check for window.location.pathname+window.location.hash
$(document).ready(function() {
if (window.location.pathname+window.location.hash == '/index.html#contact') {
console.log('Viewing contact form');
}
});
because window.location.pathname
does not include the part after the hash.
Your Html code
<div id="contact">
</div>
Your Javascript code
$("#contact").scroll(function() {
/*do whatever you want*/
});