JQuery

From XPUB & Lens-Based wiki
Revision as of 10:55, 16 February 2021 by Michael Murtaugh (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

JQuery is a JavaScript popular framework. It smooths over many of the difficulties that traditionally made JavaScript hard to work with and supports / encourages a unique style of coding driven by CSS-selector based "queries". JQuery code can be surprisingly compact. By default jQuery is accessed via the globally defined function "$" (though "jQuery" should also work).

For example, to hide all the links (in anchor tags) on a page, you could simply write:

$("a").hide();

Or to make all paragraphs of class "quote" have a pink background, and a larger text size:

$("p.quote").css({background:  "pink", font-size: "larger"});

http://jquery.org

JQuery

http://jquery.org

  • Smooths over browser differences (Event-handling, AJAX)
  • Incredibly elegant: CSS selectors to "query" the page & manipulate specific content with code
  • Pre-fab widgets & behaviors (Draggable, Resizable, Droppable)

JQuery: Hello world

<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function () {
    console.log("Hello world");
});
</head>
<body>
</body>
</html>

JQuery: Styles Plus

<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function () {
    $("p.foo").css({'background': 'pink'});
});
</head>
<body>
<p class="foo">Hello</p>
<p>World</p>
</body>
</html>

Extreme Functions

Javascript functions can be defined "in-place" and be "anonymous".

Traditional for loop:

var words = "Once upon a time, in a galaxy far far away".split(" ")

for (var i=0; i<words.length; i++) {
    console.log(words[i]);
}

Using jQuery's each:

var words = "Once upon a time, in a galaxy far far away".split(" ")
$(words).each(function (i, w) {
    console.log(w);
});

There are situations where using each is important! (For making proper closures)

JQuery: Events

<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function () {

    $("p").click(function () {
        $(this).css({background: "aqua"});
    });

});
</head>

<body>
    <p class="foo">Hello</p>
    <p>World</p>
</body>

</html>