Reputation: 167
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.
Upvotes: 3
Views: 5440
Reputation: 29337
The 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.com/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.
Upvotes: 3
Reputation: 774
Your Html code
<div id="contact">
</div>
Your Javascript code
$("#contact").scroll(function() {
/*do whatever you want*/
});
Upvotes: 1