user12894165
user12894165

Reputation:

Vanilla JavaScript in Svelte

I've been following a guide to collapse a sidebar. I realised that I cannot use the $ because it's reserved in Svelte. Can someone guide me on how to make this work? Thanks :)

$(document).ready(function () {
    $('#sidebarCollapse').on('click', function () {
        $('#sidebar').toggleClass('active');
    });
});

Upvotes: 1

Views: 2408

Answers (2)

JHeth
JHeth

Reputation: 8396

You should really read through/follow along with the Svelte tutorial, it might help you better understand how to overcome small challenges like this.

Toggling a class is as easy as toggling a variable and using Svelte's shorthand class directive

<script>
    let active = false;
</script>

<button on:click={()=> active = !active}>
    Some menu text or an icon here
</button>

<aside class:active>
    I'm a sidebar
</aside>

Then you just make the styles equal to whatever tutorial you're following along with since the active class would be conditionally applied at that point.

Here's a simple REPL example.

Upvotes: 6

Andre Nuechter
Andre Nuechter

Reputation: 2253

The equivalent vanilla js code would be:

const sidebarCollapse = document.getElementById('sidebarCollapse');
const sidebar = document.getElementById('sidebar');

sidebarCollapse.onclick = () => sidebar.classList.toggle('active');

Upvotes: 3

Related Questions