Skip to content
Advertisement

jQuery in wordpress showing warning of ‘cannot use import statement outside a module

I am a newbie developing WordPress theme but having some problems in the navigation menu. I want to open sub-menu through jQuery for certain reasons but terribly failed. Would you guys help me to get out of this problem? I have coded the following in the different php and js pages.

header.php

<div class="anilaDefaultHeader__bottom">
    <nav class="main-menu" role="navigation" aria-label="<?php esc_html_e( 'Main Navigation', 'anila' ) ?>">              
        <?php
        get_template_part( 'template/header/main-menu' );
        ?>
    </nav>
    <div class="search-area">          
        <?php get_search_form(); ?>
    </div>
</div>

/src/js/navigation.js

import $ from 'jquery';    
$( '.anilaDefaultHeader__bottom' ).on( 'mouseenter', '.menu-item-has-children' (e) =>  {
        $(.currentTarget).addClass('open');
    }).on('mouseleave', '.menu-item-has-children', (e) => {
        $(e.currentTarget).removeClass('open');
    })

/lib/anila-script.php

    function anila_custom_script() {
    wp_enqueue_style( 'style-css',get_template_directory_uri() . '/src/css/main.css' );
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
    wp_enqueue_script( 'anila_script', get_template_directory_uri() . '/src/js/navigation.js', array( 'jquery' ), '1.0.0', true);
    include( get_template_directory() . '/lib/inline-css.php' );
    wp_add_inline_style( 'style-css', $inline_styles );
}
add_action( 'wp_enqueue_scripts', 'anila_custom_script' );

Everything is functioning fine but the only submenu is not opening when I am hovering.

If I go to inspect and manually add class ‘open’, it shows correctly. but it should be opened as I hover. I went to inspect and console and find and error

**

“Cannot use import statement outside a module”

**

When I removed

import $ from 'jquery';

from the navigation.js

then this msg occurred in inspect->console

**

$ is not a function navigation.js?ver=1.0.0:2

**

Please help to fix it.

Advertisement

Answer

Try replacing $ with jQuery. That usually solves the problem for me. And do not use import. Take look here for more into this.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement