最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Vanilla JavaScript in Svelte - Stack Overflow

programmeradmin2浏览0评论

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');
    });
});

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');
    });
});
Share edited Feb 20, 2020 at 14:56 V. Sambor 13.4k6 gold badges50 silver badges67 bronze badges asked Feb 19, 2020 at 18:42 user12894165user12894165 5
  • The $ es from jQuery, not vanilla js. – Andre Nuechter Commented Feb 19, 2020 at 18:44
  • I think he's asking how to convert it to vanilla JS, but I might be wrong. @James, can you clarify? – John Montgomery Commented Feb 19, 2020 at 18:44
  • 2 you can use jQuery.noConflict() – Daniel A. White Commented Feb 19, 2020 at 18:45
  • I'm sorry yeah. How would I go about adding the '. Active' class without jquery or can I use the '$' in Svelte somehow? – user12894165 Commented Feb 19, 2020 at 18:49
  • api.jquery./jQuery.noConflict/#jQuery-noConflict-removeAll – Teemu Commented Feb 19, 2020 at 18:50
Add a ment  | 

2 Answers 2

Reset to default 6

You should really read through/follow along with the Svelte tutorial, it might help you better understand how to overe 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.

The equivalent vanilla js code would be:

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

sidebarCollapse.onclick = () => sidebar.classList.toggle('active');
发布评论

评论列表(0)

  1. 暂无评论