DEV Community

avery
avery

Posted on

17. jQuery

BootCamp by Dr.Angela

1. What is jQuery?

  • A JavaScript library that simplifies DOM manipulation
  • ex) document.querySelector("h1"); // Vanilla JS $("h1"); // jQuery

2. How to Use jQuery

  • CDN (Google Hosted Libraries) : https://developers.google.com/speed/libraries#jquery
    • <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  • Place
    • Before </body> → no timing issues (recommended)
    • Inside <head> → may cause timing issues
    • Fix timing issue : $(document).ready(function () { // jQuery code });

3. Minification

4. Selecting Elements

  • ex) $("button"); // selects all button elements

5. Manipulating Styles

  • Change CSS : ex) $("h1").css("font-size", "5rem");
  • Add class (multiple allowed) : ex) $("h1").addClass("big-title margin-50");
  • Remove class : ex) $("h1").removeClass("big-title");
  • Check class : ex) $("h1").hasClass("margin-50"); // true / false

6. Manipulating Text

  • Text only : ex) $("h1").text("Bye");
  • Includes HTML : ex) $("h1").html("<em>Hey</em>");

7. Manipulating Attributes

  • Get attribute : ex) console.log($("img").attr("src"));
  • Set attribute : ex) $("a").attr("href", "https://www.google.com");
  1. Event Listeners
  2. Vanilla JS vs jQuery : ex) for (var i = 0; i < 5; i++) { document.querySelectorAll("button")[i].addEventListener("click", function () { document.querySelector("h1").style.color = "purple"; }); } vs $("button").click(function () { $("h1").css("color", "purple"); });
  3. Key press : ex) $(document).keypress(function (event) { $("h1").text(event.key); });
  4. Mouse event : ex) $("h1").on("mouseover", function () { $("h1").css("color", "purple"); });
  5. Reference : https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Events

9. Adding and Removing Elements

  • before() : ex) $("h1").before("<button>New</button>");
  • after() : ex) $("h1").after("<button>New</button>");
  • prepend() : ex) $("h1").prepend("<button>New</button>");
  • append() : ex) $("h1").append("<button>New</button>");
  • remove() : ex) $("button").remove();

10. Animations

  • Built-in effects: hide, show, toggle, fadeOut, fadeIn, fadeToggle, slideUp, slideDown, slideToggle
    • ex) $("button").on("click", function () { $("h1").hide(); });
  • animate() (numeric values only) : ex) $("button").on("click", function () {
    $("h1").animate({ opacity: 0.5 });
    });
  • Chaining : ex) $("button").on("click", function () {
    $("h1").slideUp().slideDown().animate({ opacity: 0.5 });
    });

Top comments (0)