jQuery code need to translate to vanilla so I can use in Angular

I have this code on a template and I'm transfering the code to Angular 4 but it doesn't like the $ on jquery so I need a way to either be able to use it on Angular 4 or just translate it to pure js so I can use it.

Here's the code:

$('#toggle-btn').on('click', function (e) {

        e.preventDefault();

        if ($(window).outerWidth() > 1194) {
          $('nav.side-navbar').toggleClass('shrink');
          $('.page').toggleClass('active');
        } else {
          $('nav.side-navbar').toggleClass('show-sm');
          $('.page').toggleClass('active-sm');
        }
      });

How can I do this?

2 answers

  • answered 2017-08-16 19:29 Jim

    Without adding the jQuery package:

    declare var $: any;

    and if you need typescript definition then add this package to your package.json

    "@types/jquery": "^2.0.45",

  • answered 2017-08-16 19:29 realdubb

    How to do the same in vanillaJS.

    function toggle(elements, className){
        Object.keys(elements).forEach(element => elements[element].classList.toggle(className))
    }
    
    function handleClick(e){
        e.preventDefault();
        if (window.outerWidth > 1194) {
            toggle(document.querySelectorAll('nav.side-navbar'), 'shrink');
            toggle(document.getElementsByClassName('page'), 'active');
        } else {
            toggle(document.querySelectorAll('nav.side-navbar'), 'show-sm');
            toggle(document.getElementsByClassName('page'), 'active-sm');
        }
    }
    
    document.getElementById('toggle-btn').addEventListener('click', handleClick);