Skip to content
Advertisement

In jsfiddle, it works in pure javascript, But – when I include this in my code, it doesn’t work without jquery included [closed]

https://jsfiddle.net/c2o4j8fz/1/ – Where i get the code.

My code:

const chk = document.getElementById('chk');
const body = document.body;
$(function(){
    chk.addEventListener('change', () => {
        $('.body').toggleClass('dark');
        localStorage.setItem("blockIsActive", $('.body').hasClass('dark'));
    }) 
    var blockIsActive = localStorage.getItem("blockIsActive") 
    if (blockIsActive == "true") {
        $('.body').addClass('dark');
    }
});

My code displays this error $ is not defined in the console, until i add jQuery, but in the jsfiddle example, it works in pure js. What am I doing wrong?

Advertisement

Answer

If you check the Resources tab of that fiddle, it actually says it includes jQuery:

Screenshot of Fiddle meta

Mind that $ isn’t standard JavaScript, but a jQuery function/API to start with.

Advertisement