why is my javascript 'scrollIntoView' not working?

40 views Asked by At

I am using javascript trying to highlight and scroll to text on my html page.

(It's the same functionality as 'Ctrl-F' (find) in a browser. A school project.)

The highlight is working, which indicates my variable 'targetElement' is set correctly.

The scrolling is not working. The 'scrollIntoView' appears to be doing nothing.

I have tried:

  • changing the order of the highlighting and scrolling statements.
  • changing and completely removing 'scrollIntoView' options.
  • delaying the 'scrollIntoView' (as in the code below).
  • searching similar questions on stackoverflow

All with no effect.

        function scrollToOccurrence(currentOccurrenceIndex) {

            // reset previous span
            if (currentOccurrenceIndex > 0) {
                let targetElement = document.getElementById('span' + (currentOccurrenceIndex - 1));
                targetElement.className = 'yellow'
            }
            
            // set current span
            let targetElement = document.getElementById('span' + currentOccurrenceIndex);
            targetElement.className = 'orange'

            // scroll to the current occurrence
            setTimeout(function () {
                targetElement.scrollIntoView({ behavior: 'smooth', block: 'center'} );
            }, 500);

        }

For my testing, the only css I have is:

<style>
    .yellow {
        background: yellow;
    }
    .orange {
        background: orange;
    }
</style>
0

There are 0 answers