1

I am rather new to jquery and i'm trying to find the right offset for a div element inside the body. I want to make this div element sticky whenever I scroll down and pass the top offset of this element.

I followed this tutorial: https://www.youtube.com/watch?v=utonytGKodc and it works but I have a metaslider in my header and the width/height of this element is left out of the calculations to find the right offset....

the result is that my element becomes a sticky element way to soon, is there a way I can manualy add the sliders coordinates (offset) to the offset calculation of the element i want to make sticky?

var offerteOffset = jQuery(".agendawrap").offset().top //+ metaslider coordinates??;
    alert(offerteOffset);

    jQuery(window).scroll(function() {
        var scrollPos = jQuery(window).scrollTop();

        if (scrollPos >= offerteOffset) {
            jQuery(".agendawrap").addClass("fixed");
        } else {
            jQuery(".agendawrap").removeClass("fixed");
        }

    });
W.Romijn
  • 11
  • 1
  • 7

1 Answers1

0

I cant believe people make such bad tutorials.

First of all: dont write jQuery all the time. Have a look at this thread. Basically it says: use an invoking function with an own scope:

(function($) { /* all your jQuery goes here */ })(jQuery);

So you can just type $ instead of jQuery.

To your original question:

(function($) { 

  $(function() { // document ready...

    var scrollTolerance = 50,
      agendawrap = $(".agendawrap"),
      offerteOffset = agendawrap.offset().top;

    $(window).on('scroll', function() {
        var scrollPos = $(window).scrollTop();

        // OR: if (scrollPos - scrollTolerance >= offerteOffset) {
        if (scrollPos + scrollTolerance >= offerteOffset) {
          agendawrap.addClass("fixed");
        } 
        else {
          agendawrap.removeClass("fixed");
        }

    });

  });

})(jQuery);
Community
  • 1
  • 1
Alex
  • 9,911
  • 5
  • 33
  • 52
  • Allright thanks a lot, can you link me to a good tutorial because i would like to know how this works instead of just copy/paste – W.Romijn Nov 02 '15 at 14:11
  • ow, and i use it in wordpress i think that is why i use jQuery instead of $? @alex – W.Romijn Nov 02 '15 at 14:12
  • @W.Romijn doesnt matter in which environment you use it, you can use the above way everywhere, it is current best practice. i highly recommend you that you try to understand what is happening there. i really like that you try to understand rather than just copy/paste, so I offer you a little chat session if you are interested :) – Alex Nov 02 '15 at 15:22
  • Yea that sounds great! How can I start a chatsession? @Alex – W.Romijn Nov 04 '15 at 08:05