Event when hit element in the field of view + the upper part of the screen when scrolling the page?

Hello
There is here such script:

var target = $('.block');
 var targetPos = target.offset().top;
 var winHeight = $(window).height();
 var scrollToElem = targetPos - winHeight;

$(window).scroll(function(){
 var winScrollTop = $(this).scrollTop();
 if(winScrollTop > scrollToElem){
$(target).addClass("fixed");
 } else {
$(target).removeClass("fixed");
}
 });


The script adds to the unit .block class .fixed as soon as the block enters the field of view of the user when the page scrolls.

Can't solve the problem that the class was added not when the item enters the field of visibility, and when between the start element and the upper part of the screen is for example 30px?
June 14th 19 at 18:02
2 answers
June 14th 19 at 18:04
Solution
Yes, all would be well, but it is important to ask addclass precisely when between the element and the top of the screen left 30px.

Now made so:
var windowHeight = $(window).height();

 $(document).on('scroll', function() {
 $('.block').each(function() {
 var self = $(this), height;
 var top = $(document).scrollTop();
 height = self.offset().top + windowHeight - 30;

 if (top + windowHeight > height) {
$('.block').addClass("fixed");
 } else {
$('.block').removeClass("fixed");
}

});
 });


But this decision begins to lag (blinking when scrolling the page) when you add to the block position fixed; - earlene commented on June 14th 19 at 18:07
, var scrollToElem = targetPos - 30;
https://codepen.io/one_day/pen/XeExVB - zola.Purdy commented on June 14th 19 at 18:10
Thank you very much! Very helpful! - earlene commented on June 14th 19 at 18:13
June 14th 19 at 18:06
That is, here is the solution, but for some reason not running the else condition
$(document).on('scroll', function() {
 $('.block').each(function() {
 var self = $(this), height;
 height = self.offset().top + windowHeight - 30;

 if ($(document).scrollTop() + windowHeight >= height) {
$('.block').addClass("fixed");
 } else {
$('.block').removeClass("fixed");
}
});
 });

Find more questions by tags jQueryJavaScript