Skip to main content Link Search Menu Expand Document (external link)

jQuery

This article will show you how to install and import the jQuery library to your application.

Table Of Contents

  1. What is jQuery?
  2. Why jQuery?
  3. How to install jQuery
  4. Try jQuery

What is jQuery?

jQuery is a JavaScript library that is quick, compact, cross-platform, and feature-rich. It allows web developers to add extra functionality to their websites. It is also known as ‘write less, do more’ since it links numerous typical actions that need several lines of JavaScript code to perform into methods that can be invoked with a single line of code whenever needed.

Why jQuery?

jQuery greatly simplifies the use of JavaScript on your website. jQuery encapsulates many typical operations that require multiple lines of JavaScript code into methods that can be called with a single line of code.

How to install jQuery

Reminder:

Make sure that your containers are up and running.

Run yarn add jquery.

 root@0122:/usr/src/app# yarn add jquery
yarn add v1.22.19
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ jquery@3.6.3
info All dependencies
└─ jquery@3.6.3
Done in 2.04s.

Then go to application.js and import jQuery to our application.

// app/javascript/application.js

  // ...
+
+ import jQuery from "jquery"
+ window.jQuery = jQuery
+ window.$ = jQuery

Try jQuery

Let’s try changing our copy clipboard and implement jQuery.

// app/javascript/controllers/clipboard_controller.js

import {Controller} from "@hotwired/stimulus"

export default class extends Controller {
    static targets = ["email"]

    copy() {
        navigator.clipboard.writeText(this.emailTarget.textContent);
-       document.getElementsByClassName("notice")[0].innerText = 'copy email: ' + this.emailTarget.textContent
+       $(".notice:eq(0)").text('copy email: ' + this.emailTarget.textContent);
    }
}

Read Carefully:

  • The $(.class) is a class selector.
  • Command $(":eq(index)") selects the element at index n within the matched set.
  • Finally, text(text) sets the content of each element in the set of matched elements to the specified text.

Now we successfully integrated the jQuery in our application.


Back to top

Copyright © 2020-2022 Secure Smarter Service, Inc. This site is powered by KodaCamp.