IT박스

사용자가 특정 요소로 스크롤 할 때 이벤트 트리거-jQuery 사용

itboxs 2020. 11. 23. 07:56
반응형

사용자가 특정 요소로 스크롤 할 때 이벤트 트리거-jQuery 사용


한 페이지 아래에 h1이 있습니다 ..

<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>

사용자가 h1로 스크롤하거나 브라우저보기에 표시 할 때 경고를 트리거하고 싶습니다.

$('#scroll-to').scroll(function() {
     alert('you have scrolled to the h1!');
});

어떻게해야합니까?


offset요소를 계산 한 다음 다음과 scroll같은 값과 비교할 수 있습니다 .

$(window).scroll(function() {
   var hT = $('#scroll-to').offset().top,
       hH = $('#scroll-to').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
       console.log('H1 on the view!');
   }
});

데모 바이올린 확인


업데이트 된 데모 바이올린 경고 없음-대신 요소를 FadeIn ()


요소가 뷰포트 내부에 있는지 확인하도록 코드를 업데이트했습니다. 따라서 이것은 if 문에 몇 가지 규칙을 추가하여 위아래로 스크롤하든 상관없이 작동합니다.

   if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
       //Do something
   }

데모 바이올린


이 질문을 사용자가 페이지의 특정 부분을지나 스크롤 할 때 jQuery 트리거 작업 의 베스트 답변과 결합

var element_position = $('#scroll-to').offset().top;

$(window).on('scroll', function() {
    var y_scroll_pos = window.pageYOffset;
    var scroll_pos_test = element_position;

    if(y_scroll_pos > scroll_pos_test) {
        //do stuff
    }
});

최신 정보

요소가 맨 위가 아닌 화면의 중간에있을 때 트리거되도록 코드를 개선했습니다. 또한 사용자가 화면 하단을 누르고 함수가 아직 실행되지 않은 경우에도 코드를 트리거합니다.

var element_position = $('#scroll-to').offset().top;
var screen_height = $(window).height();
var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
var activation_point = element_position - (screen_height * activation_offset);
var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer

//Does something when user scrolls to it OR
//Does it when user has reached the bottom of the page and hasn't triggered the function yet
$(window).on('scroll', function() {
    var y_scroll_pos = window.pageYOffset;

    var element_in_view = y_scroll_pos > activation_point;
    var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;

    if(element_in_view || has_reached_bottom_of_page) {
        //Do something
    }
});

가장 좋은 방법은 바로 그 일을하는 기존 라이브러리를 활용하는 것입니다.

http://imakewebthings.com/jquery-waypoints/

요소가 뷰포트의 상단에 도달하면 시작되는 리스너를 요소에 추가 할 수 있습니다.

$('#scroll-to').waypoint(function() {
 alert('you have scrolled to the h1!');
});

사용중인 놀라운 데모 :

http://tympanus.net/codrops/2013/07/16/on-scroll-header-effects/


Inview 라이브러리 트리거 이벤트 및 jquery 1.8 이상에서 잘 작동합니다! https://github.com/protonet/jquery.inview

$('div').on('inview', function (event, visible) {
  if (visible == true) {
    // element is now visible in the viewport
  } else {
    // element has gone out of viewport
  }
});

https://remysharp.com/2009/01/26/element-in-view-event-plugin 읽기


이것이 필요한 것입니다.

자바 스크립트 :

$(window).scroll(function() {
    var hT = $('#circle').offset().top,
        hH = $('#circle').outerHeight(),
        wH = $(window).height(),
        wS = $(this).scrollTop();
    console.log((hT - wH), wS);
    if (wS > (hT + hH - wH)) {
        $('.count').each(function() {
            $(this).prop('Counter', 0).animate({
                Counter: $(this).text()
            }, {
                duration: 900,
                easing: 'swing',
                step: function(now) {
                    $(this).text(Math.ceil(now));
                }
            });
        }); {
            $('.count').removeClass('count').addClass('counted');
        };
    }
});

CSS :

#circle
{
    width: 100px;
    height: 100px;
    background: blue;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
    float:left;
    margin:5px;
}
.count, .counted
{
  line-height: 100px;
  color:white;
  margin-left:30px;
  font-size:25px;
}
#talkbubble {
   width: 120px;
   height: 80px;
   background: green;
   position: relative;
   -moz-border-radius:    10px;
   -webkit-border-radius: 10px;
   border-radius:         10px;
   float:left;
   margin:20px;
}
#talkbubble:before {
   content:"";
   position: absolute;
   right: 100%;
   top: 15px;
   width: 0;
   height: 0;
   border-top: 13px solid transparent;
   border-right: 20px solid green;
   border-bottom: 13px solid transparent;
}

HTML :

<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="circle"><span class="count">1234</span></div>

Check this bootply: http://www.bootply.com/atin_agarwal2/cJBywxX5Qp


You can use jQuery plugin with the inview event like this :

jQuery('.your-class-here').one('inview', function (event, visible) {
    if (visible == true) {
      //Enjoy !
    }
});

Link : https://remysharp.com/2009/01/26/element-in-view-event-plugin


If you are doing a lot of functionality based on scroll position, Scroll magic (http://scrollmagic.io/) is built entirely for this purpose.

It makes it easy to trigger JS based on when the user reaches certain elements when scrolling. It also integrates with the GSAP animation engine (https://greensock.com/) which is great for parallax scrolling websites


Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.

Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.

function elementInView(el) {
  // The vertical distance between the top of the page and the top of the element.
  var elementOffset = $(el).offset().top;
  // The height of the element, including padding and borders.
  var elementOuterHeight = $(el).outerHeight();
  // Height of the window without margins, padding, borders.
  var windowHeight = $(window).height();
  // The vertical distance between the top of the page and the top of the viewport.
  var scrollOffset = $(this).scrollTop();

  if (elementOuterHeight < windowHeight) {
    // Element is smaller than viewport.
    if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
      // Element is completely inside viewport, reveal the element!
      return true;
    }
  } else {
    // Element is larger than the viewport, handle visibility differently.
    // Consider it visible as soon as it's top half has filled the viewport.
    if (scrollOffset > elementOffset) {
      // The top of the viewport has touched the top of the element, reveal the element!
      return true;
    }
  }
  return false;
}

You could use this for all devices,

$(document).on('scroll', function() {
    if( $(this).scrollTop() >= $('#target_element').position().top ){
        do_something();
    }
});

Fire scroll only once after a successful scroll

The accepted answer worked for me (90%) but I had to tweak it a little to actually fire only once.

$(window).on('scroll',function() {
            var hT = $('#comment-box-section').offset().top,
                hH = $('#comment-box-section').outerHeight(),
                wH = $(window).height(),
                wS = $(this).scrollTop();

            if (wS > ((hT+hH-wH)-500)){
                console.log('comment box section arrived! eh');
                // After Stuff
                $(window).off('scroll');
                doStuff();
            }

        });

Note: By successful scroll I mean when user has scrolled to my element or in other words when my element is in view.


I use the same code doing that all the time, so added a simple jquery plugin doing it. 480 bytes long, and fast. Only bound elements analyzed in runtime.

https://www.npmjs.com/package/jquery-on-scrolled-to

It will be $('#scroll-to').onScrolledTo(0, function() { alert('you have scrolled to the h1!'); });

or use 0.5 instead of 0 if need to alert when half of the h1 shown.

참고URL : https://stackoverflow.com/questions/21561480/trigger-event-when-user-scroll-to-specific-element-with-jquery

반응형