0

I have this issue with jquery, I want to be able to use it anywhere in my application. I have installed it using npm install jquery and have imported it in my app.js file like this:

import $ from "jquery";
window.$ = $;

And in my livewire component, I have this code:

@push('scripts')
    <script>
        $(function () {
            alert("Hello");
        });
    </script>
@endpush

With this code, I get the following error: Uncaught ReferenceError: $ is not defined

And finally, I have this in my blade layout file:

@livewireScripts
<script src="{{ mix('js/app.js') }}"></script>
@stack('scripts')

This code is working only if I put it in the app.js file.

1 Answer 1

2

try replacing your import with this one:

window.$ = window.jQuery = require('jquery')

credit: How to use JQuery in Laravel (NPM) Ikbel

if this didn't work, try adding an event of loading:

<script>
window.addEventListener('load', function() {
    $(function () {
        alert("Hello");
    });
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting the same error!
try adding the jquery cdn on your layout and see if it works: <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script> (just to test)
if it works, maybe the installation you made of jquery on laravel is not correct. when you run npm install jquery, did you use npm run development or npm run dev?
Jquery works, but only when I write scripts in app.js where I import jquery.

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.