The document discusses JavaScript and jQuery. It covers how browsers work, the DOM and DOM API, jQuery library, DOM traversal and manipulation, event-driven programming, AJAX, and jQuery plugins. It provides examples and interactive demos of selecting elements with jQuery, modifying CSS classes and styles, reading and changing attributes, and inserting or removing elements to manipulate the DOM.
Over 200 Pages of resources and code snippets to learn JavaScript and JavaScript DOM manipulation. JavaScript is the most popular web programming language and this eBook will help you learn more about JavaScript Coding
Modern JavaScript, HTML5 and CSS3 techniques and examples. Thereās an endless amount of materials available around these topics so naturally this set doesnāt cover everything there is to know. Instead this is more like a summary of good techniques and practices Iāve encountered while doing web software development.
Developing large scale JavaScript applicationsMilan Korsos
Ā
Developing large scale JavaScript applications
24/11/11 @ Front end meetup, Budapest (Hungary)
www.milankorsos.com
www.twitter.com/korsosm
www.sowink.com
This is the presentation I was using when delivering the JavaScript Jump Start meetup on February 14th, 2022. More information about that meetup can be found at https://www.meetup.com/lifemichael/events/278743661/ You can find the video at https://youtu.be/F1e-KHTEKzo
JavaScript Module Patterns: How to build and use JavaScript modules. We cover the Basic Module Pattern, Revealing Module Pattern, CommonJS, AMD, CommonJS, UMD and ES6 modules.
Presented at SCREENS 2013 in Toronto with Nick Van Weerdenburg
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
AngularJS is a hot, hot, hot topic. Building web and mobile apps in AngularJS is an ease but there is a learning curve. In this session, youāll learn the ins and outs of AngularJS and leave the session knowing how to build killer AngularJS apps.
The important parts of the front end development sphere including CSS3, advanced JavaScript, libraries such as jQuery, RequireJS and Promises. And finally, chrome developer tools for successful debugging and editing.
This article is the first part of a series of articles on using JavaScript tools. Today, JavaScript is a very powerful language that can be used to build web apps, mobile apps, and even some pc games ā perhaps a bit faster than you would build them otherwise.
New libraries have emerged in the web industry to address the challenges of JavaScript ā libraries such as JQuery, Prototype and many others have been released. Today, a popular question asked by many is ā should i learn the libraries such as jQuery or learn basic JavaScript. The truth is that the libraries help you to create faster, responsive JavaScript, but there are still times when your basic knowlege of JavaScript will be called into question. It is for this reason that I have created this eBook, to assist newbies learn JavaScript.
Over 200 Pages of resources and code snippets to learn JavaScript and JavaScript DOM manipulation. JavaScript is the most popular web programming language and this eBook will help you learn more about JavaScript Coding
Modern JavaScript, HTML5 and CSS3 techniques and examples. Thereās an endless amount of materials available around these topics so naturally this set doesnāt cover everything there is to know. Instead this is more like a summary of good techniques and practices Iāve encountered while doing web software development.
Developing large scale JavaScript applicationsMilan Korsos
Ā
Developing large scale JavaScript applications
24/11/11 @ Front end meetup, Budapest (Hungary)
www.milankorsos.com
www.twitter.com/korsosm
www.sowink.com
This is the presentation I was using when delivering the JavaScript Jump Start meetup on February 14th, 2022. More information about that meetup can be found at https://www.meetup.com/lifemichael/events/278743661/ You can find the video at https://youtu.be/F1e-KHTEKzo
JavaScript Module Patterns: How to build and use JavaScript modules. We cover the Basic Module Pattern, Revealing Module Pattern, CommonJS, AMD, CommonJS, UMD and ES6 modules.
Presented at SCREENS 2013 in Toronto with Nick Van Weerdenburg
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
AngularJS is a hot, hot, hot topic. Building web and mobile apps in AngularJS is an ease but there is a learning curve. In this session, youāll learn the ins and outs of AngularJS and leave the session knowing how to build killer AngularJS apps.
The important parts of the front end development sphere including CSS3, advanced JavaScript, libraries such as jQuery, RequireJS and Promises. And finally, chrome developer tools for successful debugging and editing.
This article is the first part of a series of articles on using JavaScript tools. Today, JavaScript is a very powerful language that can be used to build web apps, mobile apps, and even some pc games ā perhaps a bit faster than you would build them otherwise.
New libraries have emerged in the web industry to address the challenges of JavaScript ā libraries such as JQuery, Prototype and many others have been released. Today, a popular question asked by many is ā should i learn the libraries such as jQuery or learn basic JavaScript. The truth is that the libraries help you to create faster, responsive JavaScript, but there are still times when your basic knowlege of JavaScript will be called into question. It is for this reason that I have created this eBook, to assist newbies learn JavaScript.
An introduction to AngularJS architecture and usage, equipped with an overview of AngularJS role in solving the problems arised along the history of web development.
For further material and updates:
http://blog.avirancohen.com
PANORAMA NECTO 14 TRAINING - Panorama is leading a Business Intelligence 3.0 revolution and a creation of a new generation of Business Intelligence & Data Discovery solutions that enable organizations to leverage the power of Social Decision Making and Automated Intelligence to gain insights more quickly, more efficiently, and with greater relevancy.
www.panorama.com
In a world dominated by React and Angular, Vue is the open source framework that brings a third alternative to the table, combining the strengths of the first two while trying to weed out their weaknesses.
The result is an easy to use, lightweight and versatile framework. In this talk we will explore Vue's architecture, see how components interact among themselves, have a look at the event model and in the end, how to wrap everything together in a SPA using Webpack.
This presentation will show the latest Web Components technologies and examples, and whether you should be using Web Components now. (spoiler alert: you should be!)
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
Ā
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Ā
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Ā
Clients donāt know what they donāt know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clientsā needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Ā
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
Ā
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
Ā
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
DevOps and Testing slides at DASA ConnectKari Kakkonen
Ā
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Ā
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Ā
Are you looking to streamline your workflows and boost your projectsā efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, youāre in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part āEssentials of Automationā series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Hereās what youāll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
Weāll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Donāt miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
Ā
As AI technology is pushing into IT I was wondering myself, as an āinfrastructure container kubernetes guyā, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefitās both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Ā
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
3. Topics Covered
How Browser Works.
DOM and DOM API.
jQuery Library.
DOM Traversal and Manipulation
Event-Driven Programming
AJAX
jQuery plugins (Bootstrap)
NOTICE: This tutorial includes interactive demo, itās better to
see html version if you currently arenāt: http:
//pa4373.github.io/jstutorials/dom_jquery.html
4. How Browser Works?
Given the following html snippet:
1 <html lang='en'>
2 <head>
3 <meta charset='utf-8'>
4 <title>Sample Page</title>
5 </head>
6 <body>
7 <div id='content'></div>
8 <script type='text/javascript'>
9 (function () {
10 var domObj = document.getElementById('content');
11 domObj.innerHTML = 'Hello World!';
12 })();
13 </script>
14 </body>
15 </html>
6. How Browser Works? (Partially)
Source ā (DOM Parser) ā DOM Tree ā (Render Engine) ā
What we saw.
1. Source code (plain text) will be parsed to DOM tree.
2. With DOM tree, browser will render content on the screen
accordingly. (with CSS, if exists.)
DOM stands for Document Object Model.
DOM Tree is essentially data represented in tree
structure.
7. DOM and DOM API
Such design enables the possibility to use a script language to
provide interaction with users.
After DOM objects were created, the script has access to those
objects via DOM API.
In the context, the script is written in JavaScript.
There might be others such as VBScript (dead already), Java
Applet. . .
Remark: The program responsible for executing JavaScript
codes called āJavaScript Engine.ā
8. DOM API (in JavaScript)
DOM API looks like this:
1 var domObj = document.getElementById('content');
2 // get dom object which 'id' is 'content'
3 var newDomObj = document.createTextNode("Water");
4 // create new dom object.
5 domObj.appendChild(newDomObj);
6 // insert new node to the selected as its child.
7 domObj.addEventListener('click', function () {
8 window.alert('WHOOOPAH!');
9 });
10 // Upon clicking the text, show the alert box.
9. DOM API (in Javascript, Contād)
It includes:
Traversal: Select DOM objects satisfying criteria.
Manipulation: Change its attributes, add / remove itās parent /
children node and such.
Event Handling: Binding functions when certain events occur,
such as click.
Basically, you operate on a tree structure.
More
10. How to write JavaScript in Browser?
Either by putting codes inline in <script> tag:
1 ...
2 <script type='text/javascript'>
3 (function () {
4 your code goes here.....
5 })();
6 </script>
7 </body>
8 </html>
or link to external ļ¬le:
1 <script type='text/javascript' src='main.js'></script>
where JavaScript codes lie in main.js.
11. How to write JavaScript in Browser? (Contād)
Where to put the script tags?
Well, it varies, the main concerns are:
1. Validity of HTML
2. Synchronous Loading (Blocking)
Validity of HTML means your code following the standard of
HTML structure.
Synchronous Loading: When browser loads your HTML, it
parses line by line, constructs DOM tree and renders
accordingly.
If it encounters script tags, either it executes immediately,
or it loads external ļ¬les.
All operations blocks the web page rendering.
12. How to write JavaScript in Browser? (Contād)
Few years ago, itās wildly recommended to put script tags at
the bottom of body section, since JS codes donāt load until
DOM tree is constructed:
However, if your codebase is quite large (think of Facebook),
your users have to wait longer for your application initialised.
For small size program, this works just ļ¬ne.
For modern browsers, you can put script tags at the
bottom of head with async or defer attributes:
1 <script type='text/javascript' src='app1.js' defer></script
2 <script type='text/javascript' src='app2.js' defer></script
Scripts with async tag executes immediately upon ļ¬le is
loaded, which is non-deterministic, while defer tag ensures
your ļ¬les executes in sequence asynchronously.
13. Debug trick
WARNING: The trick code demonstrated below shall be in
development only, remove it when itās ready to go production.
1. console.log: Print text under the JavaScript REPL. If your
input is object / array, it allows you to inspect its attribute.
Figure 2: console.log on REPL
14. Debugger
āThe formal wayā to debug your application. (see the joke)
Basic steps:
1. Navigate to the code section you would like to inspect.
2. Set proper breakpoints
3. Execute program, and the program stops at breakpoints.
4. Inspect the program state at the moment.
Details varies in diļ¬erent browsers, you might want to check
out yourself:
Firefox: https:
//developer.mozilla.org/en-UK/docs/Tools/Debugger
Chrome: https://developer.chrome.com/devtools/docs/
javascript-debugging
15. jQuery
DOM Traversal / Manipulation can be tedious, using native
API.
You need to pay attention to Cross-Browser compatibility.
Writing DOM animation can be hard, at least for me. (though
with the advent of CSS3 animation it changes.)
16. jQuery (Contād)
To address those problems, jQuery was born to simplify those
task:
1 var domObj = document.getElementById('content');
2 domObj.innerHTML = 'Hello World!';
3 // Using Native DOM API
4 $('#content').text('Hello World!');
5 // Using jQuery
Originally written by John Resig, jQuery is the most popular
JavaScript library in use today. (source)
Massive plugins to create diļ¬erent eļ¬ects.
While experienced programmers tend to reduce their
dependence on jQuery for better portability, modularity and
performance, it increases the development speed.
REMARK: jQuery is a library, and your vanilla JavaScript works
just ļ¬ne without it. (see the prank)
17. How to use jQuery
We sticks to jQuery 2.x in this tutorial.
1. You need to include it in your page at ļ¬rst.
1.1 Navigate to https://jquery.com/download/, download the
compressed, production version.
1.2 Letās assume the downloaded ļ¬le called jquery.min.js, include
it in your page:
1 <script type='text/javascript' src='jquery.min.js'></scr
1.3 Put your script tag below the jQuery tag.
2. To test if it works, put the following code and test if jQuery
works:
1 $(document).ready(function (){
2 $('body').text('jQuery works!');
3 });
(or just puts your download link in src directly.)
18. Basic Model
jQuery is a giant function (object) with an identiļ¬er, usually
with $. (jQuery itself works.)
DOM:
1. You select some elements.
2. and you either manipulate them or bind events for them.
(object method)
3. (or using jQuery to create new DOM and insert to page later.)
Not-related to DOM: Simpliļ¬ed helper function to work with.
(function, ex: jQueryās ajax function: $.ajax)
19. $(document).ready(fn)
A page canāt be manipulated safely until the document is
loaded.
Weāve seen this in Synchronous Loading.
Instead of moving around your script tag, jQuery provides a
method on document object, which binds function to event
when your page is loaded. (a.k.a ready):
1 $(document).ready(function () {
2 // your code won't run until the page is ready.
3 });
4 // your code runs as soon as loaded.
which can be simpliļ¬ed into:
1 $(function () {
2 // your code won't run until the page is ready.
3 });
Itās good habit to put your code in the supplied function.
20. DOM Traversal
In jQuery, DOM traversal can be seen as three kinds:
1. Ad-Hoc Selection: Using CSS selector to directly specify
elements in documents.
2. Relative Position Lookup: Given one node on DOM tree, ļ¬nd
its parent / children nodes.
3. Filtering current collections.
1 var contentNode = $('#content');
2 // Fetch the node with id `content`
3 contentNode.children().filter(':even')
4 .each(function () {
5 window.alert($(this).text());
6 });
7 /* Fetch its children, choose the even ones only,
8 and print out its value,
9 the form is tricky for now, but we'll see it later.*/
21. DOM Traversal (Contād)
CSS Selector: Pretty much the same as what you learned in
CSS3 part.
To inspect quickly: Fire up [Inspect Element], navigate to
[Inspector], look for desired dom object and right click [Get
Unique Selector] (Firefox)
the results you got, known as jQuery collection, which you
can manipulate later on.
When you applied method related to DOM traversal /
manipulation, jQuery returns itself, hence it supports chaining.
22. Function chaining:
Recall string example:
1 'I'm gonna be 500 Miles'
2 .replace('gonna be ', 'would walk ').toUpperCase();
3 //: "I'M WOULD WALK 500 MILES"
You can see after replace function is applied, a new string is
generated, and the new string invokes toUpperCase method
and so on..
Intuitively, The function acts as giant function (object) with
internal states change, and this case applied to jQuery, too.
REMARK: String operation is actually object wrapper.
Hence we can see jQuery collection as jQuery function with
references to selected objects.
Technical detail: You can enable chaining by return this
(current object) in your object method. See more.
23. DOM Traversal (Contād)
Consider the following HTML and JavaScript snippets, it
converts all characters to upper case:
1 <blockquote id='hawking'>
2 The victim should have the right to end his life,
3 if he wants. But I think it would be a great mistake.
4 However bad life may seem, there is always something
5 you can do, and succeed at.
6 While there's life, there is hope. ~ Stephen Hawking
7 </blockquote>
1 var hawkingQuote = $('#hawking');
2 var text = hawkingQuote.text();
3 hawkingQuote.text(text.toUpperCase());
24. DOM Traversal (Contād)
Checkout the demo:
[Hover over me to see demo.]
The victim should have the right to end his life, if he wants. But I
think it would be a great mistake. However bad life may seem, there
is always something you can do, and succeed at. While thereās life,
there is hope. ~ Stephen Hawking
25. DOM Traversal (Contād)
What happened?
1 var hawkingQuote = $('#hawking');
2 var text = hawkingQuote.html();
3 hawkingQuote.html(text.toUpperCase());
In line 1, we initialise our jQuery function with nevigating its
focus on āhawkingā object.
Itās ad-hoc selection, with jQuery collection containing one
object.
To extract its value, we call text function in line 2 and it
returns;
Then, we set its value with uppercased version of the string, in
line 3.
Although we havenāt covered DOM manipulation, yet. See
text as content getter / setter, depending on whether the
parameter is given.
26. DOM Traversal (Contād)
Another example. It converts to upper case if the item is
odd-indexed.
1 <ol id='songList'>
2 <li>Led Zeppelin - Kashmir</li>
3 <li>Billy Joel - Piano Man</li>
4 <li>John Mayer - Gravity</li>
5 <li>The Black Angels - Young Men Dead</li>
6 <li>John Mayer - Slow Dancing In A Burning Room</li
7 <li>Jimi Hendrix - Voodoo Chile</li>
8 </ol>
1 $('#songList').children().filter(':even')
2 .each(function (idx, ele) {
3 var newText = $(ele).text().toUpperCase();
4 $(ele).text(newText);
5 });
27. DOM Traversal (Contād)
Check out the demo:
[Hover over me to see demo.]
1. Led Zeppelin - Kashmir
2. Billy Joel - Piano Man
3. John Mayer - Gravity
4. The Black Angels - Young Men Dead
5. John Mayer - Slow Dancing In A Burning Room
6. Jimi Hendrix - Voodoo Chile
28. DOM Traversal (Contād)
What happened?
1 $('#songList').children().filter(':even')
2 .each(function (idx, ele) {
3 var newText = $(ele).text().toUpperCase();
4 $(ele).text(newText);
5 });
In line 1, we select songList item, get its children nodes, and
then convert some to upper case.
1. For $(ā#songListā), itās standard ad-hoc selection with one
object in jQuery collection. (ol)
2. then we use children method to get its children, itās relative
position lookup, resulted in multiple objects in collection.
(multiple li)
29. DOM Traversal (Contād)
What happened?
1 $('#songList').children().filter(':even')
2 .each(function (idx, ele) {
3 var newText = $(ele).text().toUpperCase();
4 $(ele).text(newText);
5 });
In Line 2, we choose the even elements, using filter, resulted
in the subset of the previous collection. (multiple li)
Then we ITERATE the collection, using each method.
30. DOM Traversal (Contād)
Why not for (; ;) loop?
Well, because what you got is not an array or any array-like
object.
However, it suļ¬ce to provide equivalent eļ¬ect as for loop:
inx: the current index of the object, starting from 0.
ele: the current item. To use with jQuery, pass it to $ again.
Conceptual Analogy:
1 $coll.each(function (inx, ele) {
2 // code block....
3 });
4
5 for (var inx = 0; inx < $coll.length; inx = inx + 1) {
6 var ele = $coll[inx];
7 // code block....
8 }
9 // Note this won't work in real case.
31. DOM Traversal (Contād)
In contrast to children method, parents method gets the
parent node of the current node.
For complete ad-doc selection, consult: http://api.jquery.
com/category/selectors/hierarchy-selectors/
For ļ¬ltering, consult: http:
//api.jquery.com/category/traversing/filtering/
For complete tree traversal, consult:
http://api.jquery.com/category/traversing/
This concludes the DOM traversal chapter.
32. DOM Manipulation
After you located your target collection, you can:
1. Read / Modify its CSS class and CSS style.
2. Read / Modify its attribute. (href, src . . . )
3. Insert / Remove element around them.
4. Use some built-in animations.
Based on those operations, you can even use plugins to create
astonishing eļ¬ects with little eļ¬ort.
33. DOM Manipulation (Contād)
Given the following HTML, CSS, and JavaScript snippets:
1 <blockquote id='russell'>
2 A man would not say "I hope the first President of the
3 United States will be the first President of the United
4 States" unless he had an unusual passion for the law of
5 identity. ~ Bertrand Russell, Western Philosophy
6 </blockquote>
1 .quote-border {
2 border: 1px #777 dashed;
3 margin: 5px;
4 }
1 $('#russell').addClass('quote-border');
34. DOM Manipulation (Contād)
See the live demo:
[Hover over me to see demo.]
A man would not say āI hope the ļ¬rst President of the United
States will be the ļ¬rst President of the United Statesā unless he had
an unusual passion for the law of identity. ~ Bertrand Russell,
Western Philosophy
35. DOM Manipulation (Contād)
Itās obvious that addClass will append new class to elements
class attribute.
The opposite of addClass is removeClass.
36. DOM Manipulation (Contād)
Given the following HTML and JavaScript snippets:
1 <img src='assets/hover1.jpg' id='barney'>
1 var barney = $('#barney');
2 var original = barney.attr('src');
3 // original will hold 'assets/hover1.jpg'
4 barney.attr('src', 'assets/hover2.jpg');
attr is also a setter / getter, depending on whether the
parameter is given.
in line 4, it changes its value to assets/hover2.jpg
38. DOM Manipulation (Contād)
Given the following HTML, CSS and JavaScript snippets:
1 <div id='source'>
2 Come back you little bastard!
3 </div>
4 <div id='target'>
5 Mom, I'm here!
6 </div>
1 #target {
2 border: 1px #777 solid;
3 }
1 var source = $('#source')
2 $('#target').append(source);
39. DOM Manipulation (Contād)
See the live demo: [Hover over me to see demo.]
Come back you little bastard!
Mom, Iām here!
append method will inject elements (selected by $) inside the
object.
The opposite is remove.
If you want to inject a copy instead of original one, use
$('#source').clone() instead.
Some other common methods are: after, before. . . ..
40. DOM Manipulation (Contād)
Animation: Some jQuery methods encapsulating underlying
css / time operations.
fadeIn, fadeOut: elements fade in / away in the given time
interval.
show, hide: elements show / hide immediately.
41. DOM Manipulation (Contād)
Consider the following HTML, Javascript snippets:
1 <div id='fade-away'>
2 I'm gonna be gone.
3 </div>
1 $('#fade-away').fadeOut(1000, function () {
2 window.alert('BOOM!');
3 });
42. DOM Manipulation (Contād)
See the live demo:
[Hover over me to see demo.]
Iām gonna be gone.
It shows that #fade-away object will fade out in 1000
milliseconds.
It can also be slow, fast string.
After itās completely gone, the callback will trigger, showing
one alert box.
Callback function is optional, you can disable it by simply not
giving a callback function.
44. Event-driven Programming
To make your program interact with users, your program need
to know how to respond user action.
Event: Certain action occurring upon certain elements. (ex:
click on #sampleObject)
Handler: The piece codes executed when some events are
triggered, usually represented in the form of function in
JavaScript.
You actually have seen that in previous example, while all demo
programs are triggered by hovering your mouse over certain
area.
Some rules about event-driven programming:
Bind / unbind function to elementsā event.
Event bubbling.
Avoid conļ¬ict.
45. Event-driven Programming (Contād)
Consider the following HTML, JavaScript snippets:
1 <div id='binding-target'>
2 Can't click me.
3 </div>
1 $('#binding-target').html('Can click me.')
2 .on('click', function (e) {
3 $(this).html('I was hit! not again plz!');
4 window.alert('Event Type: '+ e.type);
5 return false;
6 });
47. Event-driven Programming (Contād)
.on( events [, selector ] [, data ], handler )
on method registers function to events. (such as click,
hover. . . )
Function invoked when certain event is triggered.
Apart from browser built-in events, you can design your own
event.
In your handler function, you can supply e as event object.
The opposite of on is off
Minor: Thereās another way to invoke which supplies children
selector. It works by delegating your event to those matched
selection.
API: http://api.jquery.com/on/
48. Event-driven Programming (Contād)
DOM elements usually nested inside each other, the handler of
the parent works even if you click on itās child.
Event bubbling: After an event triggers on the deepest possible
element, it then triggers on parents in nesting order.
Sometimes it may cause problem,
For example, in this slide (web version), you go to the next by
clicking, imagine what will happened if I didnāt take precaution
(in which case of course I did, self ļ¬ve!) in the previous
example.
49. Event-driven Programming (Contād)
Remember e (as event object) in handler function?
It provides two methods:
stopPropagation: It stops itself from bubbling to the parent.
preventDefault: It prevent its default action from happening.
(such as form submitting.)
return false = stopPropagation + preventDefault +
return. (returning value does no good in handler function,
right?)
50. Event-driven Programming (Contād)
In time, you may develop more complicated program require
dynamically binding / unbinding.
Itās good habit to unbind old handler before new one is
attached:
1 $('#target-binding').off('click')
2 .on('click', function () {
3 ...});
To avoid conļ¬ict and strange behaviour, best keep your logic
simple. (think about, is there cleaner way to express equivalent
program logic?)
51. Event-driven Programming (Contād)
Shortcut: on('click', handler) can be expressed as
click(handler)
This applies to : change (when value of form changes),
submit (right before the form is submitted), and such..
53. HTTP Protocol
Application protocol underlying browser communication.
Request: client constructs a request to server. (along with
information.)
Response: server will send a response to client.
55. HTTP Protocol
The ļ¬rst part is your request header, and the second is the
response.
Request Method: what kind of operation you intended to do
on server (āGETā, āPOSTā, and etc. . . )
Status Code: The response code indicates the status of the
operation (200 for OK, 404 for not found. . . )
You can inspect the information within the browser, using
[Inspect Element] > [Network]
56. AJAX
AJAX stands for Asynchronous JavaScript and XML.
Instead of one speciļ¬c technology, AJAX is composed of several
diļ¬erent technologies, and the use of XML is not a must.
Intuitively, it use JavaScript code to retrieve partial content
from server (string mostly), and do something with the
retrieved content.
Hence it frees us from constant reloading and better
desktop-alike user experience.
57. AJAX
Generally, the AJAX procedure in JavaScript goes like:
1. Prepare your HTTP request: specify the request url, method
(GET, POST..), request parameter and callback function.
2. After you send your request, you let your callback function to
handle the rest. (known as asynchronous programming)
3. If it got data from server, usually in the form of JSON (or
XML), the callback function is invoked.
JSON (or XML) is plain string able to be converted (deserialise,
with JSON.parse) to data structure, or the other way around
(serialise, with JSON.stringify).
JSON, JavaScript Simple Object Notation: boolean, number,
string, array, object and friends. (sounds familiar?)
You can operate on the data structure in the callback function
after that.
59. $.ajax
To do AJAX in native browser API can be really tedious.
(browser compatibility mostly.)
jQuery provides $.ajax function to simplify the task.
API: http://api.jquery.com/jquery.ajax/
60. $.ajax
jQuery.ajax( url [, settings ] )
Note thereās no selection this time.
url: the request url.
settings is a object containing the detail of the request and
callback. Some common ones are:
method: HTTP method you would like to perform, such as
āGETā, āPOSTā
data: the parameters sent along with the request, can be
object ({a: 0, b: 1}), parameter string (āa=0&b=1ā)
success: A function to be called if the request succeeds.
Function( Anything data, String textStatus, jqXHR
jqXHR )
success if HTTP status code in the range of 200 to 299, or 304.
error: A function to be called if the request fails
Function( Anything data, String textStatus, jqXHR
jqXHR )
61. $.ajax
complete: A function to call after success and error is
called.
headers: You can put customised HTTP headers here.
(usually helpful when it comes to authorisation..)
62. $.ajax
Example: http://api.hostip.info/get_json.php
Please use browser to open it, you shall see:
1 {"country_name":"TAIWAN",
2 "country_code":"TW",
3 "city":"Taipei",
4 "ip":"140.112.102.93"}
This can be seen as data object in the success callback
function later.
63. $.ajax
Considering the following HTML and JavaScript:
1 <button id='what-my-ip'>What is my IP?</button>
1 $('#what-my-ip').click(function () {
2 $.ajax('http://api.hostip.info/get_json.php', {
3 method: 'GET',
4 success: function (data) {
5 window.alert('Hello sir, you came from ' +
6 data.city + ', ' + data.country_name +
7 ', and your IP address is ' + data.ip);
8 }
9 });
10 return false;
11 });
65. $.ajax
$.ajax is the core low-level interface in jQuery, there are some
shortcuts available:
$.get, $.getJSON, $.post. . .
Consult API: http:
//api.jquery.com/category/ajax/shorthand-methods/
Notice in Chrome, you need to put your website on the server
or AJAX wonāt work.
To debug with remote API, some tools comes handy:
Postman - REST Client: a tool on Google Chrome to inspect
RESTful API.
RESTClient, a debugger for RESTful web services.: Firefox
peopleās Postman.
curl: hardcore unix programmer use it. (not me.)
66. jQuery Plugins (Bootstrap)
jQuery plugins extends jQueryās functionality to allow you do
much with little eļ¬ort.
Itās impossible to cover all kind use of plugins, so the really
important thing is to know how to read plugins manual instead.
Some recommended tips:
1. Read Get started, Quick start to get the plugin run ļ¬rst.
2. If you canāt directly dump in API doc, see if some tutorial
available.
3. Read API doc carefully to know how to use.
For some non-trivial plugin, it usually involves some mental
model to understand. Get it ļ¬rst and you will learn how to use
it more eļ¬ciently.
Here, we takes Bootstrap jQuery plugins for example:
http://getbootstrap.com/javascript/