Home » Jquery » javascript – adding class to button when another element is scrolled into the viewport

javascript – adding class to button when another element is scrolled into the viewport

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have one static button and one element which scrolls. When the scrollable element enters the browser viewport, I want the static button to get a class (e.g. underline).
I have this now, but it doesn’t work:

function isScrolledIntoView(elem) {
    var docViewTop = jQuery(window).scrollTop();
    var docViewBottom = docViewTop + jQuery(window).height();

    var elemTop = jQuery(elem).offset().top;
    var elemBottom = elemTop + jQuery(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

jQuery(window).scroll(function () {
    jQuery('#my-scrolling-element').each(function () {
        if (isScrolledIntoView(this) === true) {
            jQuery('#my-static-button').addClass('my-class');
        }
    });

});

Any help would be much appreciated

How to&Answer:

if you want to add class to the element that is input type then below code will work. otherwise please provide me some code snippet.
Please accept the answer if it helps you.

jQuery(window).scroll(function() {
  element = jQuery('#my-scrolling-element');
  if (isScrolledIntoView(element) === true) {
    jQuery('#my-static-button')
    //if the type of element is input then it will work.
    $("input[id^='my-scrolling-element_']").addClass('my-class');
  } else {
    jQuery('#my-static-button').removeClass('my-class');
  }
});

//OR 
jQuery(window).scroll(function() {
  element = jQuery('#my-scrolling-element');
  if (isScrolledIntoView(element) === true) {
    jQuery('#my-static-button').addClass('my-class');
  } else {
    jQuery('#my-static-button').removeClass('my-class');
  }
});