3

Im trying to run this script with Tampermonkey but i get Error: eslint: no-undef - $ is not defined" What im doing wrong?

Script:

(function() {
    'use strict';

    restore();

    $('span.tag').each((n, span) => {
        let input = document.querySelector(`input#${span.getAttribute('for')}`);
        span.addEventListener('click', () => {
            store(`tags`, input.value, input.checked);
        });
    });
    $('#board, #title').change((e) => {
        store(e.target.id, e.target.value);
    });

    function restore(){
        let json = localStorage.getItem('create') || "{}";
        let data = JSON.parse(json);

        Object.keys(data).forEach(key => {
            switch(key){
                case "tags":
                    data[key].forEach(val => {
                        document.querySelector(`input[value="${val}"]`).setAttribute('checked', 'checked');
                        document.querySelector(`span[for="create_${val}"]`).classList.add('selected');
                    });
                    break;
                case "board":
                    document.querySelector(`#board option[value="${data[key]}"]`).setAttribute('selected', 'selected');
                default:
                    document.querySelector(`#${key}`).value = data[key];
                    break;
            }
        });
    }

    function store(key, value, checked) {
        let json = localStorage.getItem('create') || "{}";
        let data = JSON.parse(json);

        if(arguments.length === 3){
            data[key] = new Set(data[key]);
            if(checked) {
                data[key].add(value);
            } else {
                data[key].delete(value);
            }

            data[key] = Array.from(data[key]);
        } else {
            data[key] = value;
        }

        json = JSON.stringify(data);
        localStorage.setItem('create', json);
    }
})();
Mark B
  • 59
  • 1
  • 4

2 Answers2

12

You need to define global variables before everything. Just include this line at the top:

/* globals jQuery, $, waitForKeyElements */

And don't forget to require jquery between the ==UserScript== lines:

// @require      http://code.jquery.com/jquery-3.x-git.min.js
Pigmalijonas
  • 316
  • 3
  • 6
  • Where should you define this? At the top of the function, or at the top of the userscript? – Nzall Nov 27 '21 at 22:22
  • This worked for me by adding the `globals` line at the very top as the very first line of the userscript (before the `==UserScriipt==` block begins) – Ashutosh Jindal Apr 11 '23 at 14:54
1

Actually this is a annonymus function, in some cases you may have to pass jQuery

try some like:

(function($) {
'use strict';

    $('body').css('background', 'red');
})(jQuery);

how ever, you need some jquery cdn or where ever you want to use it from, included in your page where this script runs.

Dwza
  • 6,494
  • 6
  • 41
  • 73