0

I'm writing a bit of code in a custom js file located in /mytheme/js/live-search.js At the top of the js file I have [ import $ from 'jquery'; ]. In my functions.php i have my wp_enqueue_script function with the dependency of array('jquery'), but I still get an Uncaught SyntaxError: Unexpected identifier for the first line in that js file when I load the page.

I have this same setup on a local WP site I'm working on and it's working just fine there. What am I missing?

in functions.php

function asset_files() {
    wp_enqueue_script('search-jsfile', get_theme_file_uri('/js/live-search.js'), array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'asset_files');

This is the begining of my code

class Search {
    constructor() {
        this.openButton = $("#search-icon-btn");
        this.closebutton = $(".search-overlay__close");
        this.searchOverlay = $(".search-overlay");
        this.events();
    }

    events() {
        this.openButton.on("click", this.openOverlay);
        this.closebutton.on("click", this.closeOverlay);
    }

    openOverlay() {
        this.searchOverlay.addClass("search-overlay--active");
    }

    closeOverlay() {
        this.searchOverlay.removeClass("search-overlay--active");
    }
}

var liveSearch = new Search();

1 Answer 1

1

jQuery is part of WordPress core. You don't need to import it twice.

Just remove import $ from 'jquery'; in your live-search.js file.


Also, the import statement is a part of ES6 features.

To make ES6 modules work in browsers you should add type="module" to script tag like so:

<script type="module" src="filename.js"></script>
Sign up to request clarification or add additional context in comments.

8 Comments

Hey Andrew, I tried that once before and I got an "Uncaught TypeError: $ is not a function" error when it encountered my first constructor statement "this.openButtun = $("#search-icon-btn");"
Hey Patrik, try to put this in your js file: (function($) { /* Your code inside here; */ })(jQuery);
Thank you for quick responses! That worked for my constructor statements but down in the events section it's throwing me an "Uncaught TypeError: Cannot read property 'on' " error for the first a couple of these kinds of statements "this.openButton.on("click", this.openOverlay);"..... :( Am i going to end up declaring each jquery function I want to use?
What exactly error says? Cannot read property 'on' ...? Is this.openButton a jQuery object?
Sorry the error in full is "Uncaught TypeError: Cannot read property 'on' of undefined" I updated my original questions with the start of my code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.