2

I've written a script which detects if a certain string exists within the HTML of a page and then wraps the string with a span containing a class. This string can appear multiple times within the same page.

I'm then detecting when any of these elements are in view within the browser and then firing an event to display a warning to the page using jquery's show() method.

The idea is that when the element then leaves the viewport the warning is hidden using jquery's hide() method.

I've got this working when only one instance of the element is present but if thee are multiple there is a conflict between the show() and hide() methods.

$(document).ready(function(){

    $("body").html(function () {
        return $(this).html()
            .replace("word", "<span class='custom-class'>word</span>")
    });

    $(window).scroll(function() {
        $(".custom-class").each(function(){
            var top_of_element = $(this).offset().top;
            var bottom_of_element = $(this).offset().top + $(this).outerHeight();
            var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
            var top_of_screen = $(window).scrollTop();

            if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
                $('.custom-warning').show();
            } else {
                $('.custom-warning').hide();
            }
        });
    });

});

The first instance of the 'word' when in view wont ever show the warning as it is then turned off by the second instance that is not in view.

Anyone have an idea how to overcome this?

4ndyG
  • 73
  • 1
  • 9

1 Answers1

1

I assume the right behavior is: If there is a matching element within the viewport then show the warning.

This should work then:

$(window).scroll(function() {
        $('.custom-warning').hide();
        $(".custom-class").each(function(){
            var top_of_element = $(this).offset().top;
            var bottom_of_element = $(this).offset().top + $(this).outerHeight();
            var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
            var top_of_screen = $(window).scrollTop();

            if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
                $('.custom-warning').show();
            }
        });
    });

An other hint: Because scroll is firing very often i would wrap the scroll function into a debounce function.

Thomas
  • 2,431
  • 17
  • 22