08-DOM Manipulation and Jquery
08-DOM Manipulation and Jquery
jQuery
• Vyacheslav Koldovskyy
Last update: 05-Apr-2017
Agenda
• Introducing DOM
• Manipulating DOM with JavaScript
• Storages
• jQuery
• Useful links
DOM Tree
document
<!DOCTYPE html>
<html>
<head> <html>
<title>DOM Sample</title>
<style type="text/css">
table {
border: 1px solid black; <head> <body>
}
</style>
</head>
<body> <title> <style> <table>
<table>
<tbody>
DOM <tbody>
<tr> table {…
<td>Some</td> Sample
<td>Text</td>
</tr>
<tr>
<td>in a</td> <tr> <tr>
<td>Table</td>
</tr>
</tbody>
</table>
</body> <td> <td> <td>
<td>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="target" class="target">Sample Target</p>
<p class="target">Another Paragraph</p>
<p>Last Paragraph</p>
</body>
</html>
Sample: https://jsfiddle.net/6gb5zgrp/4/
Performance: https://jsperf.com/queryselectorall-vs-getelementbyid/35
Changing HTML Content
• document.getElementById(id).innerHTML = 'New_value';
• Will replace inner content of an element
<html>
<body>
<p id="target">Old text</p>
<script>
target.innerHTML = 'New text';
</script>
</body>
</html>
https://jsfiddle.net/koldovsky/8pdwvcy7/
Changing the Value of an Attribute
• document.getElementById(id).attribute = 'New_value';
• Will replace inner content of an element
<html>
<body>
<p id="target" hidden>Hidden Paragraph</p>
<script>
target.hidden = '';
</script>
</body>
</html>
https://jsfiddle.net/koldovsky/yproq6t9/
Changing HTML Style
<html>
<body>
<p id="target" style="display: none">Hidden Paragraph</p>
<script>
document.getElementById('target').style.display = '';
</script>
</body>
</html>
Intro to Event Handling
[1]
Event handling
The next way doesn't touch HTML. For adding event handler
you need to find an object that is a JavaScript model of
HTML-element.
For example, your button has id btn:
But this method doesn't work in IE. For IE you should use:
btn.attachEvent('onclick', action);
Proper ways
btn.removeEventListener('click', action);
Interesting note
Why we refer to W3C if JavaScript syntax is specified by ECMA? Because
ECMA specifies only cross-platform part of language and does not describes
any API. The browser API is determined by W3C standards. It applies to
events, DOM, storages, etc.
Event object
You can take it if you need. In W3C browsers this object will be
passed as a first parameter of event handler:
[1]
Where action was defined as:
If you don't need a default behavior, you can cancel it. Use
object event and next methods for this purpose:
http://plnkr.co/edit/rGiBPab0hwWTg8fyMmJU?p=preview
jQuery: Write Less, Do More
$(function() {
$('#target').click(function(){
$('div').hide();
});
});
Reading and Changing HTML Contents
Sample: $('div').html('<p>Hello!</p>');
Reading and Changing Class Info
• jQuery allows to read, add or remove information about class for any element.
This may be useful to change how elements shown based on predefined CSS
styles assigned to the class and much more
• These methods are:
.addClass() – adds class:
$('p').addClass('myClass');
.removeClass() – removes class:
$('p').removeClass('myClass');
.hasClass() – checks if class is assigned:
$('#myp').hasClass('myClass');
.toggleClass() – adds class if it is not assigned and vice versa: $
('#myp').toggleClass('myClass');
• These methods, like other methods of jQuery may be chained to each other:
$('p').removeClass('myClass noClass').addClass('yourClass');
jQuery Event Basics
• Using .on() method we may setup any native browser event as well
as custom events:
$( 'p' ).on( 'click', function() {
console.log( 'click' );
});
▪ Or multiple events:
$( 'input' ).on('click change', // bind listeners for
multiple events
function() {
console.log( 'An input was clicked or changed!' )
}
);
Showing and Hiding Content
• jQuery uses combination of fade and slide effects while showing and
hiding elements. It is possible to use this effects separately.
• Slide animation:
// Hide all paragraphs using a slide up animation over 0.8 seconds
$( 'p' ).slideUp( 800 );
// Show all hidden divs using a slide down animation over 0.6
seconds
$( 'div.hidden' ).slideDown( 600 );
• Fade animation:
// Hide all paragraphs using a fade out animation over 1.5 seconds
$( 'p' ).fadeOut( 1500 );
// Show all hidden divs using a fade in animation over 0.75 seconds
$( 'div.hidden' ).fadeIn( 750 );
Changing Display Based on Current Visibility State
• jQuery can also let you change a content's visibility based on its current
visibility state. Method .toggle() will show content that is currently
hidden and hide content that is currently visible. You can pass the same
arguments to .toggle() as you pass to any of the effects methods above.
// Instantaneously toggle the display of all paragraphs
$( 'p' ).toggle();
// Slowly toggle the display of all images
$( 'img' ).toggle( 'slow' );
• There are also .slideToggle() and .fadeToggle() methods:
// Toggle the display of all ordered lists over 1 second using slide
up/down
$( 'ol' ).slideToggle( 1000 );
// Toggle the display of all blockquotes over 0.4 seconds using fade
in/out
$( 'blockquote' ).fadeToggle( 400 );
Practice Task
Advanced Topics
HTML5 Web Storage Objects
HTML5
Web • window.localStorage -
Storage stores data with no
provides expiration date
two new • window.sessionStorage -
objects for stores data for one session
storing data (data is lost when the tab is
on the closed)
client
Using Storage Objects
https://jsfiddle.net/koldovsky/d4j5zuk6/
Bubbling and Capturing
<red>
<green>
<blue /> [1]
</green>
</red>
Bubbling Capturing
[3] [2]
Sample
https://jsfiddle.net/koldovsky/4rb1czbx/2/
Cookies
What are Cookies?
• To read a cookie:
var x = document.cookie;
• This code will return all cookies in one string in
name=value pairs
• To find the value of one specified cookie, we
must write a JavaScript function that searches for
the cookie value in the cookie string.
Changing and Deleting Cookie
function getCookie(cname) {
var name = cname + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return '';
}
Setting Up Events to Run Only Once
• jQuery provides method .css() that allows to read or set style data.
• If this method used as getter, it returns CSS property value of a first element that
matches selector.
Syntax: .css('propertyName')
Sample: var color = $('#myDiv').css('background-color');
• If this method used as setter, it sets CSS property values for all elements that
match selector.
Syntax:
.css(propertyName, value); // value - a value to set for the
property
.css(propertyName, function); // function - a function returning
// the value to set
.css(properties); // properties - an object of
// property-value pairs to set
Using Different Handlers for Multiple Events
Thank You!
Copyright © 2010 SoftServe, Inc.