jQuery

Šta je jQuery?

jQuery je biblioteka koja olakšava pisanje javaScript programa. U ovom prikazu jQuery-ija posebna pažnja je posvećena načinu nakoji jQuery manipuliše DOM elementima, DOM događajima i Ajax pozivima.

jQuery možete dodati u vašu web stranicu na dva načina:

  1. Download-ovanjem biblioteke sa nekog od repozitorijuma (npr. https://jQuery.com ):

    <head>
    <script src="jquery-3.3.1.min.js"></script>
    </head>
    
  2. Peuzimanjem sa nekog CDN (Content Delivery Network) repozitorijuma:

    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    

jQuery sintaksa

Osnovna sintaksa za pisanje jQuery naredbi je: $(selector).action()

  • Znak $ je skraćenica od jQuery.
  • selector služi za pronalaženje HTML elemenata.
  • action() je metoda koja se primenjuje na elemente.

Evo nekoliko primera:

$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".

Kao što se vidi iz gornjih primera, jQuery koristi CSS sintaksu za selekciju HTML elemenata.

Evo nekoliko dodatnih primera koji pokazuju bogatstvo načina na koji se mogu selektirati HTML elementi:

$("*")  Selects all elements
$(this)         Selects the current HTML element
$("p.intro")    Selects all <p> elements with class="intro"
$("p:first")    Selects the first <p> element
$("ul li:first")        Selects the first <li> element of the first <ul>
$("ul li:first-child")  Selects the first <li> element of every <ul>
$("[href]")     Selects all elements with an href attribute
$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank"
$(":button")    Selects all <button> elements and <input> elements of type="button"
$("tr:even")    Selects all even <tr> elements
$("tr:odd")     Selects all odd <tr> elements

Document Ready događaj

Ispravno je da izvršavanje jQuery naredbi ne počne pre nego što je čitav dokument učitan u brauzeru. U suprotnom moglo bi se desiti da se neka jQuery akcija na HTML dokumentu ne izvrši jer element nije prisutan.

Da se obezbedi da su svi HTML elementi prisutni koristi se sledeća konstrukcija:

$(document).ready(function(){

  // jQuery methods go here...

});

Isti efekat se postiže i na sledeći, skraćeni način:

$(function(){

  // jQuery methods go here...

});

jQuery DOM manipulisanje

jQuery ima moćne metode za promenu i manipulaciju HTML elementima i njihovim atributima.

Pomoću tri jednostavne metode, text(), html(), value(), mogu se dobiti ili menjati sadržaji elemenata:

text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val()  - Sets or returns the value of form fields

Slično tome metoda attr() omogućava da se setuje ili dobije vrednost nekog jednog ili više atributa HTML elementa.

Sledeći primeri pokazuju upotrebu gornjih metoda za pribavljanje (get) i setovanje (set) sadržaja i atributa.

Get metode:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    alert("Text: " + $("#test").text());
  });
  $("#btn2").click(function(){
    alert("HTML: " + $("#test").html());
  });
  $("#btn3").click(function(){
    alert("Value: " + $("#test").val());
  });
  $("#btn4").click(function(){
    alert($("#w3s").attr("href"));
  });
});
</script>
</head>
<body>

<p id="test">This is some <b>bold</b> text in a paragraph.</p>
<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>

<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>
<button id="btn3">Show Value</button>
<button id="btn4">Show href attribute</button>
</body>
</html>

Set metode:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("#test1").text("Hello world!");
  });
  $("#btn2").click(function(){
    $("#test2").html("<b>Hello world!</b>");
  });
  $("#btn3").click(function(){
    $("#test3").val("Dolly Duck");
  });
});
</script>
</head>
<body>

<p id="test1">This is a paragraph.</p>
<p id="test2">This is another paragraph.</p>

<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>

<button id="btn1">Set Text</button>
<button id="btn2">Set HTML</button>
<button id="btn3">Set Value</button>

</body>
</html>

Sledi lista svih jQuery metoda koji služe za manipulaciju HTML-om i CSS-om.

  • Method Description
  • addClass() Adds one or more class names to selected elements
  • after() Inserts content after selected elements
  • append() Inserts content at the end of selected elements
  • appendTo() Inserts HTML elements at the end of selected elements
  • attr() Sets or returns attributes/values of selected elements
  • before() Inserts content before selected elements
  • clone() Makes a copy of selected elements
  • css() Sets or returns one or more style properties for selected elements
  • detach() Removes selected elements (keeps data and events)
  • empty() Removes all child nodes and content from selected elements
  • hasClass() Checks if any of the selected elements have a specified class name
  • height() Sets or returns the height of selected elements
  • html() Sets or returns the content of selected elements
  • innerHeight() Returns the height of an element (includes padding, but not border)
  • innerWidth() Returns the width of an element (includes padding, but not border)
  • insertAfter() Inserts HTML elements after selected elements
  • insertBefore() Inserts HTML elements before selected elements
  • offset() Sets or returns the offset coordinates for selected elements (relative to the document)
  • offsetParent() Returns the first positioned parent element
  • outerHeight() Returns the height of an element (includes padding and border)
  • outerWidth() Returns the width of an element (includes padding and border)
  • position() Returns the position (relative to the parent element) of an element
  • prepend() Inserts content at the beginning of selected elements
  • prependTo() Inserts HTML elements at the beginning of selected elements
  • prop() Sets or returns properties/values of selected elements
  • remove() Removes the selected elements (including data and events)
  • removeAttr() Removes one or more attributes from selected elements
  • removeClass() Removes one or more classes from selected elements
  • removeProp() Removes a property set by the prop() method
  • replaceAll() Replaces selected elements with new HTML elements
  • replaceWith() Replaces selected elements with new content
  • scrollLeft() Sets or returns the horizontal scrollbar position of selected elements
  • scrollTop() Sets or returns the vertical scrollbar position of selected elements
  • text() Sets or returns the text content of selected elements
  • toggleClass() Toggles between adding/removing one or more classes from selected elements
  • unwrap() Removes the parent element of the selected elements
  • val() Sets or returns the value attribute of the selected elements (for form elements)
  • width() Sets or returns the width of selected elements
  • wrap() Wraps HTML element(s) around each selected element
  • wrapAll() Wraps HTML element(s) around all selected elements
  • wrapInner() Wraps HTML element(s) around the content of each selected element

jQuery događaji

jQuery ima takođe vrlo bogat izbor metoda kojima se mogu opslužiti razlićiti DOM događaji.

Evo kompletnog spisak metoda sa kratkim opisom:

  • Method / Property Description
  • blur() Attaches/Triggers the blur event
  • change() Attaches/Triggers the change event
  • click() Attaches/Triggers the click event
  • dblclick() Attaches/Triggers the double click event
  • event.currentTarget The current DOM element within the event bubbling phase
  • event.data Contains the optional data passed to an event method when the current executing handler is bound
  • event.delegateTarget Returns the element where the currently-called jQuery event handler was attached
  • event.isDefaultPrevented() Returns whether event.preventDefault() was called for the event object
  • event.isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was called for the event object
  • event.isPropagationStopped() Returns whether event.stopPropagation() was called for the event object
  • event.namespace Returns the namespace specified when the event was triggered
  • event.pageX Returns the mouse position relative to the left edge of the document
  • event.pageY Returns the mouse position relative to the top edge of the document
  • event.preventDefault() Prevents the default action of the event
  • event.relatedTarget Returns which element being entered or exited on mouse movement
  • event.result Contains the last/previous value returned by an event handler triggered by the specified event
  • event.stopImmediatePropagation() Prevents other event handlers from being called
  • event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
  • event.target Returns which DOM element triggered the event
  • event.timeStamp Returns the number of milliseconds since January 1, 1970, when the event is triggered
  • event.type Returns which event type was triggered
  • event.which Returns which keyboard key or mouse button was pressed for the event
  • focus() Attaches/Triggers the focus event
  • focusin() Attaches an event handler to the focusin event
  • focusout() Attaches an event handler to the focusout event
  • hover() Attaches two event handlers to the hover event
  • keydown() Attaches/Triggers the keydown event
  • keypress() Attaches/Triggers the keypress event
  • keyup() Attaches/Triggers the keyup event
  • mousedown() Attaches/Triggers the mousedown event
  • mouseenter() Attaches/Triggers the mouseenter event
  • mouseleave() Attaches/Triggers the mouseleave event
  • mousemove() Attaches/Triggers the mousemove event
  • mouseout() Attaches/Triggers the mouseout event
  • mouseover() Attaches/Triggers the mouseover event
  • mouseup() Attaches/Triggers the mouseup event
  • off() Removes event handlers attached with the on() method
  • on() Attaches event handlers to elements
  • one() Adds one or more event handlers to selected elements. This handler can only be triggered once per element
  • $.proxy() Takes an existing function and returns a new one with a particular context
  • ready() Specifies a function to execute when the DOM is fully loaded
  • resize() Attaches/Triggers the resize event
  • scroll() Attaches/Triggers the scroll event
  • select() Attaches/Triggers the select event
  • submit() Attaches/Triggers the submit event
  • trigger() Triggers all events bound to the selected elements
  • triggerHandler() Triggers all functions bound to a specified event for the selected elements

Ovde ćemo dati primere za neke najčešće korišćene metode.

Primer:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });
  $("p").hover(function(){
    $(this).css("background-color", "#ff0000");
  });
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

Metoda on() omogućava da elementu pridružimo više događaja, kao u sledećem primeru:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p").on({
    mouseenter: function(){
      $(this).css("background-color", "lightgray");
    },
    mouseleave: function(){
      $(this).css("background-color", "lightblue");
    },
    click: function(){
      $(this).css("background-color", "yellow");
    }
  });
});
</script>
</head>
<body>

<p>Click or move the mouse pointer over this paragraph.</p>

</body>
</html>

jQuery Ajax

Ajax (Asynchronous JavaScript and XML) je jedan važan javaScript mehanizam koji omogućava da se razmenjuju podaci sa serverom i da se menjaju delovi web stranice bez ponovnog učitavanja cele stranice.

Mi smo se još ranije upoznali sa standardnim Ajax zahtevima:

function AjaxZahtev(metod, putanja, podaci, callback) {
  var req = new XMLHttpRequest();
  req.open(metod, putanja, true);
  req.addEventListener("load", function() {
    if (req.status < 400) {
      callback(req.responseText);
    }
    else {
      callback(new Error("Request failed: " + req.statusText));
    }
  });
  req.addEventListener("error", function() {
      callback(new Error("Network error"));
  });
  req.send(podaci || null);
}

jQuery ima više metoda koje koriste Ajax. Sa ovim metodama možete od servera zahtevati tekst, HTML, XML ili JSON korišćenjem i GET i POST. Možete, takođe, u neki HTML elemet postaviti eksterne podatke dobijene od servera.

jQuery load() Metoda

Sintaksa:

$(selector).load(URL,data,callback);

:

  • URL je obavezan parametar koji upućuje na resurs koji želite da load-ujete.
  • data je opcioni (nije obavezan) parametar koji se serveru šalju podaci u obliku key/value parova.
  • callback je opcioni parametar kojim se imenuje finkcija koja će biti izvršena nakon što se load() operacija završi.

Na primer:

$("#div1").load("demo_test.txt");

Moguće je čak u zahtevu postaviti i jQuery selector kao u sledećem primeru:

$("#div1").load("demo_test.txt #p1");

callback funkcija može imati sledeće opcione parametre:

  • responseTxt - contains the resulting content if the call succeeds
  • statusTxt - contains the status of the call
  • xhr - contains the XMLHttpRequest object

Ilustracija korišćenja ovih parametara data je u sledećem primeru:

$("button").click(function(){
  $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
    if(statusTxt == "success")
      alert("External content loaded successfully!");
    if(statusTxt == "error")
      alert("Error: " + xhr.status + ": " + xhr.statusText);
  });
});

jQuery $.get() Metod

Sintaksa:

$.get(URL,data,function(data,status,xhr),dataType)

Evo jednog primera:

<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function() {
                $("#driver").click(function(event) {
                        $.get(
                         "result.php", {
                             name: "GFG"
                         },
                         function(data) {
                             $('#stage').html(data);
                         });
                    });
        });
    </script>
</head>
<body>
    <p>Click on the button to load result file </p>
    <span id="stage" style="background-color:#cc0;"> GeeksForGeeks </span>
    <div> <input type="button" id="driver" value="Load Data" /></div>
</body>
</html>

PHP program:

// Result.php file
<?php
if( $_REQUEST["name"] ) {
   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
}
?>

jQuery $.post() Metod

Sintaksa:

$(selector).post(URL,data,function(data,status,xhr),dataType)

Kompletna lista jQuery Ajax metoda:

  • Method Description
  • $.ajax() Performs an async AJAX request
  • $.ajaxPrefilter() Handle custom Ajax options or modify existing options before each request is sent and before they are processed by
  • $.ajaxSetup() Sets the default values for future AJAX requests
  • $.ajaxTransport() Creates an object that handles the actual transmission of Ajax data
  • $.get() Loads data from a server using an AJAX HTTP GET request
  • $.getJSON() Loads JSON-encoded data from a server using a HTTP GET request
  • $.getScript() Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request
  • $.param() Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
  • $.post() Loads data from a server using an AJAX HTTP POST request
  • ajaxComplete() Specifies a function to run when the AJAX request completes
  • ajaxError() Specifies a function to run when the AJAX request completes with an error
  • ajaxSend() Specifies a function to run before the AJAX request is sent
  • ajaxStart() Specifies a function to run when the first AJAX request begins
  • ajaxStop() Specifies a function to run when all AJAX requests have completed
  • ajaxSuccess() Specifies a function to run when an AJAX request completes successfully
  • load() Loads data from a server and puts the returned data into the selected element
  • serialize() Encodes a set of form elements as a string for submission
  • serializeArray() Encodes a set of form elements as an array of names and values

Dobar tutorijal i referentnu listu svih jQuery metoda možete naći na W3Scool sajtu

Napominjemo da jQuery ima i jako puno “plug-in” dodataka razvijenih od strane nezavisnih developera. Postoji i regitstar tih dodataka koji možete videti OVDE