Search code examples
javascripttypescriptstenciljs

Change StencilJS component on window scroll


Is it possible to change styling of a StencilJS component when the window it is used on is scrolled?

I have the following code:

import { h } from '@stencil/core';
import { Component, Prop } from '@stencil/core'

@Component({
    tag: 'example-component',
    styleUrl: './example-component.css',
    shadow: true
})
export class ExampleComponent{
    @Prop() some_text: string;
    render(){
        return  [
          <p class="someText">{this.some_text}</p>,
          <script type="text/javascript">
            var text = document.querySelector(".someText");
            window.addEventListener('scroll', function(e) {
              text.classList.add("newClassName")
            });
          </script>
        ]
    }
}

And it doesn't work. I want to add a new class to the text when the window is scrolled, how can I achieve this?


Solution

  • Your JavaScript code should no be part of what's rendered.

    Didn't tried out the following code but a start could looks like the following:

    import { h, Listen, State, Component, Prop } from '@stencil/core';
    
    @Component({
        tag: 'example-component',
        styleUrl: './example-component.css',
        shadow: true
    })
    export class ExampleComponent {
        @Prop() some_text: string;
    
        @State() myClass: string | undefined = undefined;
    
        @Listen('scroll', {target: 'window'})
        onScroll() {
           this.myClass = 'newClassName';
        }
    
        render() {
            return <p class={this.myClass}>{this.some_text}</p>
        }
    }
    

    For references you could check the following part of the Stencil doc.