How to use JQuery in Laravel (NPM)

15,456

Solution 1

Make sure your resources/assets/js/bootstrap.js got jQuery imported:

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

Then you'll be able to use jQuery in your project.

Solution 2

JQuery is already installed within your project. To use it place the reference within your view.

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

and run npm run dev

Solution 3

all the submitted answer are correct, but i want to add that you need to put reference for your js/app.js as that is where your javascript and jquery file is and you need it to make it work. MORE importantly, you need to write it in every views that requires spesific javascript/jquery function

<script src="{{ asset('js/app.js') }}"></script>

Share:
15,456
HansMuff
Author by

HansMuff

Updated on June 26, 2022

Comments

  • HansMuff
    HansMuff almost 2 years

    Im new to web development and I work with the Laravel framework. I use npm for handling with packages. But now I have a problem to implement JQuery. Bootstrap is implemented to larval and it works

    <link rel="stylesheet" href="/css/app.css">
    

    In my Laravel project is in the package.json

     "devDependencies": {
        "axios": "^0.15.3",
        "bootstrap-sass": "^3.3.7",
        "cross-env": "^3.2.3",
        "jquery": "^3.1.1",
        "laravel-mix": "0.*",
        "lodash": "^4.17.4",
        "vue": "^2.1.10",
        "webpack": "2.2.1"
      }
    

    Does that mean that Jquery is already in my project? But how looks the link like above from Bootstrap for jquery. For Bootstrap I have to compile new code (npm run dev) have I to do the same for Jquery?

    • Tpojka
      Tpojka over 6 years
      You have to execute command npm run dev or npm run production. Check whole this page. Running that command Laravel's mix will include jQuery into app.js.
  • Hmerman6006
    Hmerman6006 almost 3 years
    After running npm install jquery --save-dev, placing this solution in the same named file before running npm run dev worked in Laravel 8! Thanks.
  • w3spi
    w3spi over 2 years
    Many thanks, Great !