simplifies most common tasks, including
- manipulating DOM
- adding/removing styles
- making network requests
- document traversal
- Download zip files (or clone git repos) for JQuery and JQuery templates
https://github.com/jquery/jquery
https://github.com/codepb/jquery-template
-
(Unzip), enter folder for JQuery and build it via
npm run build
. This will create adist
folder. Copy eitherjquery.js
(development) orjquery.min.js
(production) into your project folder. -
Likewise, copy
jquery.loadTemplate.js
orjquery.loadTemplate.min.js
from JQuery templatedist
folder into your project folder. -
Link these files in your project HTML file(s) (see below).
- define template
- create data used in template
- load and render template
- create script tag
- put whatever html you want to contain and define the template to be, giving data-content the values of the fields in your JSON data
- make JQuery call to
loadTemplate()
on the template's HTML container ID, passing the template's ID and the data to theloadTemplate()
method
Components Code
<script type="text/html" id=templateID">
<div id="ContainerID">
<div data-content="field1"></div>
<div data-content="field2"></div>
<div data-content="field3"></div>
</div>
</script>
{
"field1" : "some text data",
"field2" : 100,
"field3" : "some other string"
}
$("ContainerID").loadTemplate("templateID", data);
Template Example (Internal)
SimpleTemplate.html:
<!DOCTYPE html>
<html>
<head>
<title>Simple jQuery Template Example</title>
<link rel="stylesheet" href="../styles.css">
<script type="text/javascript" src="../jquery-1.10.2.js"></script>
<script type="text/javascript" src="../jquery.loadTemplate-1.3.2.js"></script>
<script type="text/javascript">
function renderTemplates(e) {
$("#container").loadTemplate($("#itemTemplate"), [{
"name" : "Henry Handsome",
"phone" : "+1-212-555-1234",
"email" : "[email protected]",
"title" : "Senior VP of Basketweaving",
"fulltime" : true
}, {
"name" : "Penelope Persistent",
"phone" : "+1-212-555-8000",
"email" : "[email protected]",
"title" : "Principal Understudy",
"fulltime" : false
}, {
"name" : "Sam Serendipity",
"phone" : "+1-212-555-9876",
"email" : "[email protected]",
"title" : "Chief Cook and Bottle Washer",
"fulltime" : true
}, {
"name" : "Tom Terriffic",
"phone" : "+1-212-555-0011",
"email" : "[email protected]",
"title" : "Janitor",
"fulltime" : false
}]);
}
window.addEventListener("load", renderTemplates);
</script>
</head>
<body>
<script type="text/html" id="itemTemplate">
<div class="itemTemplateWrapper">
<div data-content="name"></div>
<div data-content="title"></div>
<div data-content="email"></div>
<div data-content="phone"></div>
</div>
</script>
<h1>Simple Templates with jQuery Template</h1>
<h3>This example embeds the template directly in the source HTML</h3>
<!-- This is the container where the templates will be instantiated -->
<div id="container"></div>
</body>
</html>
Template Example (External)
ExternalTemplate.html - must be run from a server (can't simply be opened locally in a browser as it'll cause an XHR CORS policy violation)
<!DOCTYPE html>
<html>
<head>
<title>External jQuery Template Example</title>
<link rel="stylesheet" href="../styles.css">
<script type="text/javascript" src="../jquery-1.10.2.js"></script>
<script type="text/javascript" src="../jquery.loadTemplate-1.3.2.js"></script>
<script type="text/javascript">
$("document").ready(function() {
// load the template from the external file
$("#container").loadTemplate("template.html", [{
"name" : "Henry Handsome",
"phone" : "+1-212-555-1234",
"email" : "[email protected]",
"title" : "Senior VP of Basketweaving",
"fulltime" : true
}, {
"name" : "Penelope Persistent",
"phone" : "+1-212-555-8000",
"email" : "[email protected]",
"title" : "Principal Understudy",
"fulltime" : false
}, {
"name" : "Sam Serendipity",
"phone" : "+1-212-555-9876",
"email" : "[email protected]",
"title" : "Chief Cook and Bottle Washer",
"fulltime" : true
}, {
"name" : "Tom Terriffic",
"phone" : "+1-212-555-0011",
"email" : "[email protected]",
"title" : "Janitor",
"fulltime" : false
}], {
isFile : true
});
});
</script>
</head>
<body>
<h1>External Templates with jQuery Template</h1>
<h3>This example loads an external template from an HTML file</h3>
<!-- This is the container where the templates will be instantiated -->
<div id="container"></div>
</body>
</html>
- takes value of data field and formats or transforms it in some way, e.g., making it uppercase
- done via
addTemplateFormatter()
- define
data-format
attribute - add any options via
data-format-options
attribute
Formatter Example
<!DOCTYPE html>
<html>
<head>
<title>jQuery Template With Formatters Example</title>
<link rel="stylesheet" href="../styles.css">
<script type="text/javascript" src="../jquery-1.10.2.js"></script>
<script type="text/javascript" src="../jquery.loadTemplate-1.3.2.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$.addTemplateFormatter("UpperCaseFormatter", function(value, options) {
return value.toUpperCase();
});
// load the template from the external file
$("#container").loadTemplate("templateFormat.html", [{
"name" : "Henry Handsome",
"phone" : "+1-212-555-1234",
"email" : "[email protected]",
"title" : "Senior VP of Basketweaving",
"fulltime" : true
}, {
"name" : "Penelope Persistent",
"phone" : "+1-212-555-8000",
"email" : "[email protected]",
"title" : "Principal Understudy",
"fulltime" : false
}, {
"name" : "Sam Serendipity",
"phone" : "+1-212-555-9876",
"email" : "[email protected]",
"title" : "Chief Cook and Bottle Washer",
"fulltime" : true
}, {
"name" : "Tom Terriffic",
"phone" : "+1-212-555-0011",
"email" : "[email protected]",
"title" : "Janitor",
"fulltime" : false
}]);
});
</script>
</head>
<body>
<h1>Using Formatters with jQuery Template</h1>
<h3>This example uses a Formatter to process the contents of the data</h3>
<!-- This is the container where the templates will be instantiated -->
<div id="container"></div>
</body>
</html>
-
paging allows splitting data up into navigable pages as with google search results page 1 of x, etc.
-
binding allows
prepend
or inserting templated content at beginning of template container instead of replacing existing contents -
it also allows
append
, or inserting content at the end of existing template container contents -
other binding options via the following callbacks:
option | description |
---|---|
complete() |
called when data is inserted, regardless of success |
success() |
called when template data is successfully inserted into document |
error() |
invoked when error occurs during generation of templated data |
beforeInsert() |
called right before populated template is inserted into document |
afterInsert() |
invoked right after templated content is inserted into document |
Paging Example
<!DOCTYPE html>
<html>
<head>
<title>jQuery Template Paging Example</title>
<link rel="stylesheet" href="../styles.css">
<script type="text/javascript" src="../jquery-1.10.2.js"></script>
<script type="text/javascript" src="../jquery.loadTemplate-1.3.2.js"></script>
<script type="text/javascript">
var curPage = 1;
var templateData = null;
function getData() {
$.getJSON("../templateData.json", function(data) {
templateData = data;
renderTemplates(templateData, curPage);
});
}
function renderTemplates(data, pageNo) {
$("#container").loadTemplate($("#itemTemplate"), data["employees"],
{paged: true, pageNo: pageNo, elemPerPage: 1});
}
window.addEventListener("load", function(e) {
$.addTemplateFormatter("EmailLink", function(value, options) {
return "mailto:" + value;
});
document.querySelector("#prevPage").addEventListener("click", function (evt) {
if (curPage > 1) {
renderTemplates(templateData, --curPage);
}
});
document.querySelector("#nextPage").addEventListener("click", function (evt) {
if (curPage < 4) {
renderTemplates(templateData, ++curPage);
}
});
getData();
});
</script>
</head>
<body>
<script type="text/html" id="itemTemplate">
<div class="itemTemplateWrapper">
<div data-content="name"></div>
<div data-content="title"></div>
<div data-content="email" data-link="email" data-format="EmailLink" data-format-target="link"></div>
<div data-content="phone"></div>
</div>
</script>
<h1>Using jQuery Template Data Paging</h1>
<h3>This example uses the Paging and Binding Attributes features</h3>
<!-- This is the container where the templates will be instantiated -->
<div id="container"></div>
<button id="prevPage">Previous</button>
<button id="nextPage">Next</button>
</body>
</html>
Binding Example
<!DOCTYPE html>
<html>
<head>
<title>jQuery Template Paging Example</title>
<link rel="stylesheet" href="../styles.css">
<script type="text/javascript" src="../jquery-1.10.2.js"></script>
<script type="text/javascript" src="../jquery.loadTemplate-1.3.2.js"></script>
<script type="text/javascript">
// When making multiple calls to loadTemplate(), using the append or prepend options
// can add content to the template container instead of completely replacing it
function renderTemplates() {
$("#container").loadTemplate($("#itemTemplate"), {
"name" : "John Doe",
"hometown" : "Anywhere, US"
},
{append: true, beforeInsert: onBefore, afterInsert: onAfter, complete: onComplete});
$("#container").loadTemplate($("#itemTemplate"), {
"name" : "Jane Doe",
"hometown" : "Anytown, US"
},
{append: true, beforeInsert: onBefore, afterInsert: onAfter, complete: onComplete});
$("#container").loadTemplate($("#itemTemplate"), {
"name" : "John Q Public",
"hometown" : "Pleasantville, US"
},
{append: true, beforeInsert: onBefore, afterInsert: onAfter, complete: onComplete});
}
function onBefore(data) {
console.log("Content about to be inserted: " + data);
}
function onAfter(data) {
console.log("Content has been inserted: " + data);
}
function onComplete() {
console.log("Operation complete");
}
window.addEventListener("load", function(e) {
renderTemplates();
});
</script>
</head>
<body>
<script type="text/html" id="itemTemplate">
<div class="itemTemplateWrapper">
<div data-content="name"></div>
<div data-content="hometown"></div>
</div>
</script>
<h1>Using jQuery Template Data Paging</h1>
<h3>This example uses the Paging and Binding Attributes features</h3>
<!-- This is the container where the templates will be instantiated -->
<div id="container"></div>
<button id="prevPage">Previous</button>
<button id="nextPage">Next</button>
</body>
</html>
- JQuery basics
- select basic DOM elements
- use more complex selectors
- element attributes
jQuery("selector") // returns JQuery object containing all elements matching selector, among other things
// alias: jQuery -> $
$("selector")
very similar to css selectors
see: https://flukeout.github.io/
jQuery selector | description |
---|---|
$(*) |
all elements on page; very slow, not recommended |
`$("[h1 | p |
$(".my-class") |
class selector |
$("p.selected") |
combined selector for element and class |
$("#content-wrap") |
id selector |
$("p, .my-class, #my-favorite-element") |
multiple selector |
selector | description |
---|---|
`$("h1:[first | last]")` |
`$("table td:[even | odd]")` |
$("p:eq(#)") |
element index is equal to # |
$("p:gt(#)") |
element index is greater than # |
$("p:lt(#)") |
element index is less than # |
$("p:contains('jQuery')") |
select paragraphs containing text 'jQuery' |
$("p:not(.selected)") |
select elements which do not have '.selected' class |
select elements based on values of their attributes
jQuery selector | description |
---|---|
$('a[href!="google.com") |
select element of type 'href' with value not of "google.com" |
$('button[onclick]') |
select all buttons which have an onclick value (set to anything) |
$('a[href*="google.com"]') |
select all links whose address includes (but isn't limited to) google.com |
$('a[href^="https://"]') |
select all links that start with https:// |
$('[p$="Don't Panic"]') |
select all p which end with "Don't Panic" |
$('input[type="text"][onchange]') |
select all text type inputs with an 'onchange' attribute (AND) |
$('input[type="text"], [onchange]') |
all input elements of type 'text' OR, all elements with an onchange method |
$("[onclick]") |
all elemnts of any type with an onclick attribute |
- add to inner content of selected element(s) via
.append()
and.prepend()
$("p").append("<button>Click Me</button>")
$("p").prepend("First of all, ")
- add new content outside of selected element via
.before()
and.after()
$("p").before("<h1>Heading!</h1>")
$("p").after("<div>...</div>")
- add new content around (before and after) selected element(s) via
.wrap()
and.wrapAll()
wrap()
treats each element individually, wrapping each separatelywrapAll()
treats all elements as a single element, wrapping them once, together
$("p").wrap("<div>...</div>")
$("table td").wrapAll("<div>...</div>")
- instead of passing strings as arguments, we can also pass selected elements
- jQuery will copy the selected element and insert it if need be
$("p").before($("#my-favorite-heading"))
- can reverse order of statement, placing the element at the end and the passed item first
- might make code more readable
.append()
-->.appendTo()
.prepend()
-->.prependTo()
.before()
-->.insertBefore()
.after()
-->.insertAfter()
$('p').append('<span>words words</span>')
-->
$("<span>words words</span>").appendTo('p')
- remove elements from the DOM with
.remove()
or.detach()
, which also allows reinsertion elsewhere .empty()
is more heavy-handed, deleting all content from inside selected element(s) (going through all levels inside that selected).unwrap()
removes whatever element is currently surrounding the selected element(s); can optionally pass a selector with the call, which ensures matching to selector before unwrapping- replace selected element(s) with the provided argument with
.replaceWith()
replaceAll()
is the reverse of.replaceWith()
$("h1").remove()
$("#my-heading").detach().insertBefore("p:eq(3)")
$("h1").unwrap(".wrapper")
$("h1").replaceWith("<h1>Hello!</h1>")
$("<h1>Hello</h1>").replaceAll("h1")
- modify attributes/properties with
.attr()
- modify styles with ``
$("h1").attr("myAttribute")
returns value of "myAttribute" attribute for first h1 element
$('a').attr('href', 'google.com')
sets first a href value to google.com
attributes - characteristics of HTML elements we can see in HTML doc itself (id, type, value)
properties - corresponding DOM-node objects for HTML elements we defined, rendered in the browser (node.id, node.type, node.value)
-
some attributes and their corresponding properties are equivalent (id), some are not (value)
-
remove an attribute or property, respectively, with
removeAttr()
orremoveProp()
$('p').css('color', 'red')
$('h3').attr('class', 'card')
adds the class 'card' to all h3 elements
-
browser and doc events
-
mouse and keyboard events
-
Event object
-
web forms
-
event handlers are blocks of code that get called any time a particular type of event occurs for which we are listening
-
add event listeners for almost any type of event with
.on("event", callback)
Event Handling Examples
function sayHi() {
console.log("Hello!");
}
$("p").on("mouseenter mouseleave", sayHi);
or, using an anonymous function instead:
$("p").on("click", function() {
$(this).css("color", "red");
});
.trigger()
triggers an event on the selected element(s)
$("button").trigger("click")
$("p").off()
remove all event handlers from all paragraph elements$("p").off("click")
remove all click event handlers from paragraph elements$("p").off("click", sayHi)
remove the 'sayHi' callback from the "click" event for all paragraph elements (more than one callback function can be added to a single event listener)
- triggered listeners will propagate to all containing wrapper elements
- this is not desirable in the case of a button, for example
- to fix this, we need to call
.stopPropagation()
$('p').on('click', function(e) {
console.log('Clicked p');
e.stopPropagation();
});
- events that come from the document/page use
.ready()
which is called when the DOM is ready and page is finished loading (can't manipulate DOM until it's ready) - without using
.ready()
, would need to put scripts at end of page so they run after everything else loads from top to bottom
$(document).read(function() {
console.log("DOM is ready!");
})
// or
$(document).ready(callback);
// shortcut syntax:
$(callback);
.resize()
event occurs whenever window is resized.scroll()
event occurs whenever a scrollbar is scrolled- both are short-hand for using
.on("ready", ...)
and.on("scroll", ...)
Browser Events Examples
$(window).resize(function() {
console.log("Window resized!");
})
$(window).scroll(function() {
console.log("Window scrolled!");
})
.click()
or.on("click", ...)
.dblclick()
,.mouseenter()
,.mouseleave()
.keydown()
,.keypress()
,.keyup()
- keyboard methods only work with certain elements (input but not p, etc.)
- to get them to work with p, need to assign
tabindex=0
.keypress()
only triggers on alphanumeric key presses, but.keydown()
is triggered by any key- calling any of these without an argument triggers the actual event on selected element(s)
$('#my-element').keydown(function(event) {
event.keyCode; // -> 98
event.key; // -> "b"
})
- use
event.target()
to get element that event is happening to - use
e.pageX
ande.pageY
to find out where on the page an event occurred - use
e.stopPropagation()
inside event handler to stop an event from propagating up into wrapper/containing elements - to explore the event object in the console, just print the event itself, via
console.log(event);
$(selector).[event-type](function(event) {
// code, using event argument
})
.focus()
event is triggered whenever certain elements gain focus, such as text inputs.change()
is triggered whenever the value of one of the form elements changes; ex. - can use to limit # of chars for a given text input.val()
is used to get or set the value of an element, i.e., text inside a text input element.select()
triggers when user selects/highlights text inside an element; by default, only works withinput
andtextarea
.blur()
triggers when user removes focus from a given element.submit()
triggers when a form is submitted and usually involves communicating with a server
Form Events Examples
$('#my-input').focus(function() {
console.log('Element gained focus!');
});
$('#my-input').change(function(e) {
const newValue = e.target.value;
if(newValue.length > 5) {
$(e.target).val( newValue.substring(0, 5) );
}
});
$('#my-input').select(function() {
console.log(window.getSelection().toString());
});
$('#my-input').blur(function() {
console.log('Element lost focus!');
});
$.ajax({ ..., ... })
is used to make AJAX (Asynchronous JavaScript and XML) network requestsjqXHR
is a request object describing any sort of error which occurs- shortcut methods:
$.get()
and$.post()
done()
for adding success callback to request we just made.fail()
for adding error callback.always()
for adding callback executed no matter the request outcome
AJAX Syntax Examples
$.ajax({
url: 'api.my-site.com/path',
success: function(result) {
// code
},
error: function(jqXHR, textStatus, errorThrown) {
// handle error
},
type: 'GET", // or 'POST', etc.
data: JSON.stringify({ ... }), // update data on server via JSON object (or XML)
contentType: 'application/json',
})
$.get(
'api.my-site.com',
function(result) {
// do something
},
};
$.post(
'api.my-site.com',
{ a: 1, b: 2 },
function(results) {
// do something
},
});
Example To-Do List App (w/node backend not shown)
const escapeHtml = (str) =>
str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
const createTodo = () => {
// const newTodoText = $('#new-todo-input').prop('value');
const newTodoText = $('#new-todo-input').val();
$.ajax({
type: 'POST',
url: `http://localhost:8000/todos`,
data: JSON.stringify({ text: escapeHtml(newTodoText) }),
contentType: 'application/json',
success: function(todos) {
setTodos(todos);
$('#new-todo-input').val('');
},
});
}
const addTodo = (todo) => {
console.log("Adding todo");
console.log(todo);
$('#todos-list').append(`
<div class="todo">
<h3>${todo.text}</h3>
${todo.isCompleted
? '<p>Complete!</p>'
: ''}
${todo.isCompleted
? `<button onclick="deleteTodo('${ escapeHtml(todo.id) }')">Delete</button>`
: `<button onclick="markTodoAsCompleted('${ escapeHtml(todo.id) }')">Mark As Completed</button>`}
</div>
`);
};
const setTodos = (todos) => {
$('#todos-list').empty();
todos.forEach(todo => addTodo(todo));
}
const markTodoAsCompleted = (id) => {
$.ajax({
type: 'PUT',
url: `http://localhost:8000/todos/${id}/completed`,
success: function(todos) {
console.log(todos);
setTodos(todos);
},
});
}
const deleteTodo = (id) => {
$.ajax({
type: 'DELETE',
url: `http://localhost:8000/todos/${id}`,
success: function(todos) {
setTodos(todos);
},
});
}
$(() => {
$.ajax({
url: 'http://localhost:8000/todos',
success: function(todos) {
setTodos(todos);
},
});
});
.hide()
to set element display css property to none; takes optional time, type and callback parameters.show()
to show a hidden element; takes same optional parameters.toggle()
combination of the previous two - does the opposite of the current state
$('#my-element').hide(1000, 'swing', // or 'linear' for animation type
function() {
console.log('Finished hiding!');
},
};
- change color, size, shadow, chain together, etc.
.animate()
passes attributes and new values- JQueryUI library expands the options
- queue - series of animations played one after the other
.animate(
{ width: '400px' },
1000,
'swing',
function() { ... }
)
.delay()
to create a delay before a given animation, used in chaining
$('#my-element')
.animate({ width: '400px' })
.delay(1000)
.animate({ height: '500px' });
.queue()
returns an array of all animations set up for an element, has many features.stop()
pauses an animation.stop(true)
pause, clearing all scheduled animations.stop(true, true)
clears all scheduled animations and jumps to the end of what animation would have been (fast-forward)
-
make elements disappear and reappear by fading and sliding
-
fadeOut()
causes element to fade out and disappear -
fadeIn()
-
fadeToggle()
-
fadeTo()
fade to given opacity (see-through) -
slideUp()
-
slideDown()
-
slideToggle()
-
all of these take arg specifying duration of animation, either text 'fast', 'slow', or numerical - 1000 (ms)
- returns numerical value in pixels; only works on one/first element selected
.height()
.width()
.innerHeight()
- includes padding.innerWidth()
- includes padding.outerHeight()
has an optional boolean to include mragin (content, padding, border only otherwise).outerWidth()
has an optional boolean to include margin (content, padding, border only otherwise)
-
.find()
used after selecting element(s) and wanting to search through descendants/child elements -
.children()
returns all child elements of a given element we've selected -
.parent()
and.parents()
methods used to get parent or all ancestor elements of the selected element -
.siblings()
selects all elements which are the children of the selected element's parent element -
.each()
takes a selection array and a function, processing each element through the given function -
.filter()
allows us to select a subset of a selection array by the given criteria, such as all the input elements which the user hasn't entered values into, for example; -
.
The following puts a red border around all input elements which contain a string of length zero (no value entered yet):
$('input').filter(function(i. element) {
return $(element).val().length === 0;
}).css('border', '1px solid red');
.has()
takes a selection we've made and narrows it down using the selector we've provided as an argument to it
$('div').has('h3')
returns all div elements which contain an h3 element
.is()
returns true or false depending on whether given calling element has the selector we've passed as an argument
$('button').click(function() {
if($(this).is(':even')) {
console.log("I'm even!");
} else {
console.log("I'm odd!");
}
});