3

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.

Jack Hanna
  • 169
  • 2
  • 3
  • 15
  • duplicate of http://stackoverflow.com/questions/6271237/detecting-when-user-scrolls-to-bottom-of-div-with-jquery – Katya Pavlenko May 10 '15 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 May 10 '15 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 May 10 '15 at 16:23

2 Answers2

3

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.

user2314737
  • 27,088
  • 20
  • 102
  • 114
1

Your Html code

<div id="contact">

</div>

Your Javascript code

 $("#contact").scroll(function() {
/*do whatever you want*/
    });
amansinghgusain
  • 764
  • 5
  • 17