jQuery Library, Selectors, DOM Manipulation, Events, Plugins

Slides:



Advertisements
Similar presentations
The jQuery library. What is jQuery ? A javascript lightweight library Is very easy to use Is powerful Is cross-browser compatible Downloadable from jQuery.com,
Advertisements

Twitter Bootstrap. Agenda What is it? Grids and Fluid layouts Globals and Typography Tables, Forms and Buttons Navigation Media and thumbnails Responsive.
Cascading Style Sheets
Programming Club IIT Kanpur. Work environment Before you begin coding,always set up your work environment to your needs IDE Notepad++ Sublime Text 2.
Today CSS HTML A project.
Very quick intro HTML and CSS. Sample html A Web Title.
JQuery A Javascript Library Hard things made eas(ier) Norman White.
Principles of Web Design 5 th Edition Chapter Nine Site Navigation.
CSW131 Steven Battilana 1 CSW 131 – Chapter 5 (More) Advanced CSS Prepared by Prof. B. for use with Teach Yourself Visually Web Design by Ron Huddleston,
Web Pages and Style Sheets Bert Wachsmuth. HTML versus XHTML XHTML is a stricter version of HTML: HTML + stricter rules = XHTML. XHTML Rule violations:
Web Design with Cascading Style Sheet Lan Vu. Overview Introduction to CSS Designing CSS Using Visual Studio to create CSS Using template for web design.
Week 12: JQuery Write less, do more.. JQuery Basics Lightweight JavaScript Library – Emphasizes interaction between JavaScript and HTML – Reduces technical.
Philly.NET Hands-On jQuery + Plug-ins Bill Wolff, Rob Keiser.
JQuery CS 268. What is jQuery? From their web site:
PhpXperts What is jQuery Javascript Library Fast and concise Simplifies the interaction between HTML and JavaScript.
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Unleash the Power of jQuery Doncho Minkov Telerik Software Academy academy.telerik.com Senior Technical Trainer
Principles of Web Design 6 th Edition Chapter 9 – Site Navigation.
SASS & LESS Syntactically Awesome StyleSheets Dynamic StyleSheet Language Svetlin Nakov Technical Trainer Software University
Unleash the Power of jQuery Learning & Development Team Telerik Software Academy.
JQuery JavaScript is a powerful language but it is not always easy to work with. jQuery is a JavaScript library that helps with: – HTML document traversal.
JQuery Overview Unleash the Power of jQuery SoftUni Team Technical Trainers Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Bootstrap Front-End Framework for Responsive Web Sites Svetlin Nakov Technical Trainer Software University
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Stylizing a Navigational Menu Web Design Section 6-3 Part or all of this lesson was adapted from the University of Washington’s “Web Design & Development.
 Add one element at a time  If it doesn’t do what you want, › Delete it › DON’T just keep piling on more items.
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
DOM, jQuery, AJAX, REST Using Kinvey as JS Back-End
CSS (Cascading Style Sheets). CSS CSS – Cascading Style Sheets – Cascade because of the way CSS rules can stack on top of each other. Allows you to add.
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
JQuery is a fast, small, and feature-rich javascript library. It makes things like HTML document traversal and manipulation, event handling, animation,
WebD Introduction to CSS By Manik Rastogi.
JQuery Element & Attribute Selectors, Events, HTML Manipulation, & CSS Manipulation.
HTML & CSS (Super Quick Overview)
Helpers, Data Validation
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
Cookies, Sessions, Bootstrap
WordPress Introduction
Create / Delete DOM Elements Handle Browser Events
Build a WordPress Site A Real Life Example: Create a Fully Functional WP Business Web Site from Scratch Building a WP Site SoftUni Team Technical Trainers.
Source Control Systems
Bootstrap 3 SoftUni Team Technical Trainers Software University
State Management Cookies, Sessions SoftUni Team State Management
Browser Routing Design Patterns in JS
Databases advanced Course Introduction SoftUni Team Databases advanced
Unleash the Power of jQuery
MVC Architecture. Routing
Creating React Components with JSX and Babel
Install and configure theme
Front-End Framework for Responsive Web Sites
MVC Architecture, Symfony Framework for PHP Web Apps
AJAX and jQuery AJAX AJAX Concepts, XMLHttpRequest, jQuery AJAX: $.ajax(), $.get(), $.post() jQuery AJAX XMLHttpRequest SoftUni Team Technical Trainers.
ASP.NET MVC Introduction
Creating UI elements with Handlebars
Web Fundamentals (HTML and CSS)
WordPress Plugins Popular WP Plugins: Sliders, Forms, Contacts, SEO, Forum, Photo Gallery, e-Commerce WordPress Plugins SoftUni Team Technical Trainers.
Extending functionality using Collections
Making big SPA applications
CSS Transitions and Animations
Directives & Forms Capturing User Input SoftUni Team
CSS Transitions and Animations
Iterators and Generators
Fixed Positioning.
jQuery The Easy JavaScript Nikolay Chochev Technical Trainer
HTML5 and Local Storage.
Introduction to Cascading Style Sheets (CSS)
Introduction to Styling
Presentation transcript:

jQuery Library, Selectors, DOM Manipulation, Events, Plugins SoftUni Team Technical Trainers Software University http://softuni.bg

Table of Contents jQuery Overview jQuery Selectors DOM Manipulation Handling Events jQuery Plugins

Have a Question? sli.do #jquery

What is jQuery? jQuery is a cross-browser JavaScript library Dramatically simplifies DOM manipulation Simplifies AJAX calls and working with RESTful services Free, open-source software: https://jquery.com <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> Load jQuery from its official CDN $('li').css('background', '#DDD'); Change the CSS for all <li> tags

Why jQuery? Very popular Easy to learn Large community 60 000 000 sites use jQuery (75.8% of top 1 million sites) http://trends.builtwith.com/javascript/jQuery Easy to learn Large community Cross-browser support Official web site: http://jquery.com

Using jQuery from CDN <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script> $(document).ready(function() { $("a").click(function(event) { alert("Link forbidden!"); event.preventDefault(); });

Using jQuery from Local Script <script src="jquery-3.1.1.min.js"></script> <p>This is a <a href="https://softuni.bg">link</a>. </p><ul><li>one</li><li>two</li><li>three</li></ul> $(document).ready(function() { $("body *").click(function(event) { $(this).fadeOut(); $(document.body).append( "Removed: " + this + "<br>\n"); event.preventDefault(); event.stopPropagation(); });

Selection with jQuery jQuery selectors return a collection matched items Even if there is only one item http://learn.jquery.com/using-jquery-core/selecting-elements/ Selected elements can be processed as a group $('div') // document.getElementsByTagName('div'); $('.menu-item') // document.getElementsByClassName('.menu-item'); $('#navigation') // document.getElementById('navigation'); $('ul.menu li') // document.querySelectorAll('ul.menu li'); $('div').css('background', 'blue'); // Make all DIVs blue

jQuery Selectors DOM elements selection in jQuery is much like as in JavaScript All selector Class selector Element selector Id selector Multi-selector $('*') // Selects all elements $('.class') // Selects all elements by class name $('section') // Selects all elements by tag name $('#id') // Selects a element by given id $('selector1, selector2') // Combined selector © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Filter Selectors in jQuery $('li:even') // Even <li> $('li:odd') // Odd <li> $('li:first') // First <li> $('li:last') // Last <li> $('li:first-child') // Selects the first child of <li> $('li:has(p)') // Selects all <li> holding <p> inside $('li:contains("Sofia")') // Selects <li> holding given text $('li:eq(2)') // Selects the third <li> element $('li:not(:checked)') // Elements not matching the selector

Problem: Text from List An HTML page holds a list of text items + [Extract Text] button Write a JS function to display all list items, separated by ","

Problem: Text from List – HTML <ul id="items"> <li>first item</li> <li>second item</li> <li>third item</li> </ul> <button onclick="extractText()"> Extract Text</button> <div id="result"></div>

Solution: Text from List function extractText() { let items = $("ul#items li") .toArray() .map(li => li.textContent) .join(", "); $("#result").text(items); } Check your solution here: https://judge.softuni.bg/Contests/329

Problem: Search in List A HTML page holds a list of towns + search box + [Search] button Write a JS function to highlight all towns holding the search text

Problem: Search in List – HTML <ul id="towns"> <li>Sofia</li> <li>Pleven</li> <li>Varna</li> <li>Plovdiv</li> </ul> <input type="text" id="searchText" /> <button onclick="search()">Search</button> <div id="result"></div>

Solution: Search in List function search() { let searchText = $('#searchText').val(); let matches = 0; $("#towns li").each((index, item) => { if (item.textContent.includes(searchText)) { $(item).css("font-weight", "bold"); matches++; } else $(item).css("font-weight", ""); }); $('#result').text(matches + " matches found."); } Check your solution here: https://judge.softuni.bg/Contests/329

Altering the DOM with jQuery Adding and Removing DOM Elements

Adding Elements with jQuery Select the parent element, then use: append() / prepend() appendTo() / prependTo() <div id="wrapper"> <div>Hello, student!</div> <div>Goodbye, student!</div> </div> $('#wrapper div').append("<p>It's party time :)</p>"); $('<h1>Greetings</h1>').prependTo('body');

Creating / Removing Elements let div = $('<div>'); div.text('I am a new div.'); div.css('background', 'blue'); div.css('color', 'white'); $(document.body).append(div); let paragraph = $('<p>Some text</p>'); paragraph.appendTo(div); $('div').remove();

Problem: Countries Table You are given a HTML table holding countries with their capital Implement add / delete / move up / move down actions for the table rows Initially add these countries: Bulgaria / Sofia Germany / Berlin Russia / Moscow

Problem: Countries Table – HTML <style> td, th { background: #DDD; padding: 5px 10px } input[type='text'] { width: 60px } </style> <table id="countriesTable"> <tr><th>Country</th><th>Capital</th><th>Action</th></tr> <tr><td><input type="text" id="newCountryText" /></td> <td><input type="text" id="newCapitalText" /></td> <td><a href="#" id="createLink">[Create]</a></td> </tr> </table> <script>$(() => initializeTable())</script>

Solution: Countries Table – Initialize Table function initializeTable() { $("#createLink").click(createCountry); addCountryToTable("Bulgaria", "Sofia"); addCountryToTable("Germany", "Berlin"); addCountryToTable("Russia", "Moscow"); fixRowLinks(); // Functions addCountryToTable(country, capital), createCountry(), moveRowUp(), moveRowDown(), deleteRow(), fixRowLinks() come here … }

Solution: Countries Table – Create Country function createCountry() { let country = $('#newCountryText').val(); let capital = $('#newCapitalText').val(); addCountryToTable(country, capital, true); $('#newCountryText').val(''); $('#newCapitalText').val(''); fixRowLinks(); }

Solution: Countries Table – Add Country Row function addCountryToTable(country, capital) { let row = $('<tr>') .append($("<td>").text(country)) .append($("<td>").text(capital)) .append($("<td>") .append($("<a href='#'>[Up]</a>").click(moveRowUp)) .append(" ") .append($("<a href='#'>[Down]</a>").click(moveRowDown)) .append($("<a href='#'>[Delete]</a>").click(deleteRow))); row.css('display','none'); $("#countriesTable").append(row); row.fadeIn(); }

Solution: Countries Table – Row Up function moveRowUp() { let row = $(this).parent().parent(); row.fadeOut(function() { row.insertBefore(row.prev()); row.fadeIn(); fixRowLinks(); }); }

Solution: Countries Table – Row Down function moveRowDown() { let row = $(this).parent().parent(); row.fadeOut(function() { row.insertAfter(row.next()); row.fadeIn(); fixRowLinks(); }); }

Solution: Countries Table – Delete Row function deleteRow() { let row = $(this).parent().parent(); row.fadeOut(function() { row.remove(); fixRowLinks(); }); }

Solution: Countries Table – Fix Row Links function fixRowLinks() { // Show all links in the table $('#countriesTable a').css('display', 'inline'); // Hide [Up] link in first table data row let tableRows = $('#countriesTable tr'); $(tableRows[2]).find("a:contains('Up')") .css('display', 'none'); // Hide the [Down] link in the last table row $(tableRows[tableRows.length - 1]).find("a:contains('Down')") }

Handling Events with Ease jQuery Events Handling Events with Ease

jQuery Events: Attach / Remove Attaching events on certain elements $('a.button').on('click', buttonClicked); function buttonClicked() { $('.selected').removeClass('selected'); $(this).addClass('selected'); // "this" is the event source (the hyperlink clicked) } Removing event handler from certain elements $('a.button').off('click', buttonClicked);

Problem: Link Buttons – HTML <head> <link rel="stylesheet" href="link-buttons.css" /> <script src="jquery-3.1.1.min.js"></script> <script src="link-buttons.js"></script> </head> <body onload="attachEvents()"> <a class="button">Sofia</a> <a class="button">Plovdiv</a> <a class="button">Varna</a> </body>

Problem: Link Buttons – CSS a.button { border: 1px solid #CCC; background: #EEE; padding: 5px 10px; border-radius: 5px; color: #333; text-decoration: none; display: inline-block; margin: 5px; } a.button.selected { color: #111; font-weight: bold; border: 1px solid #AAA; background: #BBB; } a.button.selected::before { content: "\2713\20\20"; a:hover {cursor: pointer;}

Solution: Link Buttons – JavaScript link-buttons.js function attachEvents() { $('a.button').on('click', buttonClicked); function buttonClicked() { $('.selected').removeClass('selected'); $(this).addClass('selected'); // "this" is the event source (the hyperlink clicked) } Check your solution here: https://judge.softuni.bg/Contests/329

jQuery Events: Multiple Handling events on multiple elements Add a handler on the parent element function onListItemClick() { $('.selected').removeClass('selected'); $(this).addClass('selected'); } $('ul').on('click', 'li', onListItemClick);

Problem: Selectable Towns An HTML page listing towns Clicking on a town should select / deselect it A button shows all selected towns <style>li { display: inline-block }</style> <ul id="items"><li>Sofia</li><li>Varna</li>…</ul> <button id="showTownsButton">Show Towns</button> <div id="selectedTowns"></div> <script>$(()=>attachEvents())</script>

Solution: Selectable Towns – Click Towns function attachEvents() { $('#items').on('click', 'li', function() { let li = $(this); if (li.attr('data-selected')) { li.removeAttr('data-selected'); li.css('background', ''); } else { li.attr('data-selected', 'true'); li.css('background', '#DDD'); } }); Attach attribute 'data-selected' = 'true' to each selected <li>

Solution: Selectable Towns – Show Towns $('#showTownsButton').on('click', function() { let selLi = $('#items li[data-selected=true]'); let towns = selLi.toArray() .map(li => li.textContent).join(', '); $('#selectedTowns') .text("Selected towns: " + towns); }); } Check your solution here: https://judge.softuni.bg/Contests/329

jQuery Plugins

jQuery Plugins jQuery has many ready-to-use plugins Plugins for UI E.g. the jQueryUI library for UI controls Plugins for UI Tabs – https://jqueryui.com/tabs/ Arrangeable elements (with drag and drop) https://jqueryui.com/sortable/#display-grid $('#tabs-holder').tabs(); $('#grid').sortable();

Creating jQuery Plugins (function($) { $.fn.highlight = function(className) { $(this).on("mouseover", function() { $(this).addClass(className); }); $(this).on("mouseout", function() { $(this).removeClass(className); } }(jQuery)); $(".item").highlight('big');

Using the Highlight jQuery Plugin <style> .item { border: 1px solid #DDD } .big { font-size: 1.5em; font-weight: bold; } </style> <span class="item">First</span> <span class="item">Second</span> <span class="item">Third</span> <script>$(".item").highlight('big'); </script>

Practice: Using jQuery Live Exercises in Class (Lab)

Summary jQuery is very powerful on DOM manipulation Very popular library, run on 60 000 000 sites Select + edit DOM elements: Create elements: Handle events: $('p.red').css('background', 'blue'); $('<h1>Hello</h1>').appendTo('body'); $('#items').click(function() { … });

jQuery Library https://softuni.bg/courses/javascript-advanced © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.