Mandalina
Mandalina

Reputation: 446

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?

Upvotes: 0

Views: 1131

Answers (1)

David Dal Busco
David Dal Busco

Reputation: 8692

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.

Upvotes: 2

Related Questions