jQuery is a JavaScript library that simplifies HTML document manipulation and event handling. It allows developers to select elements, hide/show elements, and handle events with simple and concise code. jQuery animations and effects like fade, slide, and animate allow for creative transitions between states.
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
( ** Full Stack Masters Training: https://www.edureka.co/masters-program/full-stack-developer-training ** )
This PPT on jQuery will help you understand the basics of jQuery and you will also be able to create your own program using jQuery by the end of this PPT.
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
( ** Full Stack Masters Training: https://www.edureka.co/masters-program/full-stack-developer-training ** )
This PPT on jQuery will help you understand the basics of jQuery and you will also be able to create your own program using jQuery by the end of this PPT.
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
JavaScript Events:
HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can "react" on these events.
What can JavaScript Do?
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
If you are using jQuery, you need to understand the Document Object Model and how it accounts for all the elements inside any HTML document or Web page.
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
JavaScript Events:
HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can "react" on these events.
What can JavaScript Do?
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
If you are using jQuery, you need to understand the Document Object Model and how it accounts for all the elements inside any HTML document or Web page.
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
Mobile applications Development - Lecture 12
Javascript
jQuery (Zepto)
useful microframeworks
This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).
http://www.di.univaq.it/malavolta
How to increase Performance of Web Application using JQuerykolkatageeks
Pallab Dutta presented a wonderful session on how to increase productivity of web application using JQuery. He showed us demos regarding basic syntax of JQuery.
Follow us
www.kolkatageeks.com
to get more.
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
What are Events?
All the different visitors' actions that a web page can respond to are called events.
An event represents the precise moment when something happens.
Examples:
moving a mouse over an element
selecting a radio button
clicking on an element
The term "fires/fired" is often used with events. Example: "The keypress event is fired, the moment you press a key".
It covers:
- What is jQuery?
- Why jQuery?
- How include jQuery in your web page
- Creating and manipulating elements
- Events
- Animations and effects
- Talking to the server
- jQuery UI
- Writing plugins
- Breaking news around new releases
- Using the CDN
Angular Js Get Started - Complete CourseEPAM Systems
Angular Js Advantages.Developed by Google - Most Popular, SPA (Single Page Appplications), Data Binding, Easy to Test.
Complete guide for Angular Js. Covers Basics of Angular - Module, Controllers, Filters, and Advanced topics Routing, Services, UI-Routing
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
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
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.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
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.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
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.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
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.
2. INTRODUCTION
•jQuery is an Open-Source JavaScript framework that
simplifies cross-browser client side scripting.
• Animations
• DOM manipulation
• AJAX
• Extensibility through plugins
•jQuery was created by John Resig and released 01/06
•Most current release is 1.4.2 (2/19/10)
3. BENEFITS OF JQUERY
• Improves developer efficiency
• Excellent documentation // pats self on back
• Unobtrusive from the ground up
• Reduces browser inconsistencies
• At its core, a simple concept
4. JQUERY
jQuery is a JavaScript Library.
jQuery greatly simplifies JavaScript
programming.
jQuery is easy to learn.
5. WHAT IS JQUERY?
jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use
JavaScript on your website.
jQuery takes a lot of common tasks that require many lines of
JavaScript code to accomplish, and wraps them into methods
that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from
JavaScript, like AJAX calls and DOM manipulation.
The jQuery library contains the following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
Tip: In addition, jQuery has plugins for almost any task out
there.
6. ADDING JQUERY TO YOUR
WEB PAGES
There are several ways to start using jQuery on
your web site. You can:
Download the jQuery library from jQuery.com
Include jQuery from a CDN, like Google
7. DOWNLOADING JQUERY
There are two versions of jQuery available for
downloading:
Production version - this is for your live
website because it has been minified and
compressed
Development version - this is for testing and
development (uncompressed and readable
code)
Both versions can be downloaded
from jQuery.com.
The jQuery library is a single JavaScript file, and
you reference it with the HTML <script> tag
(notice that the <script> tag should be inside
the <head> section):
8. JQUERY CDN
You can include it from a CDN (Content Delivery Network).
Both Google and Microsoft host jQuery.
To use jQuery from Google or Microsoft, use one of the
following:
Google CDN:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquer
y/3.1.1/jquery.min.js"></script>
</head>
Microsoft CDN:
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jqu
ery-3.1.1.min.js"></script>
</head>
9. JQUERY SYNTAX
The jQuery syntax is tailor-made for selecting HTML
elements and performing some action on the
element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
12. DO SOMETHING
1.Let elements "listen" for something to
happen …
the document is ready
user does something
another "listener" acts
a certain amount of time elapses
13. DO SOMETHING
2.… and then do something
a.Manipulate elements
b.Animate elements
c.Communicate with the server
14. This is to prevent any jQuery code from
running before the document is finished
loading (is ready).
It is good practice to wait for the
document to be fully loaded and ready
before working with it. This also allows
you to have your JavaScript code before the
body of your document, in the head
section.
Here are some examples of actions that
can fail if methods are run before the
document is fully loaded:
Trying to hide an element that is not
created yet
15. The jQuery team has also created an
even shorter method for the document
ready event:
$(function(){
// jQuery methods go here...
});
16. JQUERY SELECTORS
jQuery selectors allow you to select and
manipulate HTML element(s).
jQuery selectors are used to "find" (or select)
HTML elements based on their name, id,
classes, types, attributes, values of attributes
and much more. It's based on the existing CSS
Selectors, and in addition, it has some own
custom selectors.
All selectors in jQuery start with the dollar sign
and parentheses: $().
17. THE ELEMENT SELECTOR
The jQuery element selector selects elements based on the
element name.
You can select all <p> elements on a page like this:
$("p")
Example
When a user clicks on a button, all <p> elements will be
hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
18. THE #ID SELECTOR
The jQuery #id selector uses the id attribute of an HTML tag to
find the specific element.
An id should be unique within a page, so you should use the
#id selector when you want to find a single, unique element.
To find an element with a specific id, write a hash character,
followed by the id of the HTML element:
$("#test")
Example
When a user clicks on a button, the element with id="test" will
be hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
19. THE .CLASS SELECTOR
The jQuery class selector finds elements with a specific
class.
To find elements with a specific class, write a period
character, followed by the name of the class:
$(".test")
Example
When a user clicks on a button, the elements with
class="test" will be hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
23. CSS ATTRIBUTE SELECTORS
$('input[name=firstname[]]')
$('[title]') has the attribute
$('[attr="val"]') attr equals val
$('[attr!="val"]') attr does not equal val
$('[attr~="val"]') attr has val as one of space-
sep. vals
$('[attr^="val"]') attr begins with val
$('[attr$="val"]') attr ends with val
$('[attr*="val"]') attr has val anywhere within
26. FUNCTIONS IN A SEPARATE
FILE
If your website contains a lot of pages, and you want
your jQuery functions to be easy to maintain, you can put
your jQuery functions in a separate .js file.
When we demonstrate jQuery in this tutorial, the
functions are added directly into the <head> section.
27. JQUERY EVENT
All the different visitor's actions that a web page can
respond to are called events.
An event represents the precise moment when
something happens.
Examples:
moving a mouse over an element
selecting a radio button
clicking on an element
The term "fires/fired" is often used with events. Example:
"The keypress event is fired, the moment you press a
key".
29. JQUERY SYNTAX FOR EVENT
METHODS
In jQuery, most DOM events have an equivalent jQuery
method.
To assign a click event to all paragraphs on a page, you
can do this:
$("p").click();
The next step is to define what should happen when the
event fires. You must pass a function to the event:
$("p").click(function(){
// action goes here!!
});
30. CLICK()
The click() method attaches an event handler function to
an HTML element.
The function is executed when the user clicks on the
HTML element.
The following example says: When a click event fires on a
<p> element; hide the current <p> element:
Example
$("p").click(function(){
$(this).hide();
});
31. DBLCLICK()
The dblclick() method attaches an event handler function
to an HTML element.
The function is executed when the user double-clicks on
the HTML element:
Example
$("p").dblclick(function(){
$(this).hide();
});
32. MOUSEENTER()
The mouseenter() method attaches an event handler
function to an HTML element.
The function is executed when the mouse pointer enters
the HTML element:
Example
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
Try it Yourself »
33. MOUSELEAVE()
The mouseleave() method attaches an event handler
function to an HTML element.
The function is executed when the mouse pointer leaves
the HTML element:
Example
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
34. MOUSEDOWN()
The mousedown() method attaches an event handler
function to an HTML element.
The function is executed, when the left, middle or right
mouse button is pressed down, while the mouse is over
the HTML element:
Example
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
35. MOUSEUP()
The mouseup() method attaches an event handler
function to an HTML element.
The function is executed, when the left, middle or right
mouse button is released, while the mouse is over the
HTML element:
Example
$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});
36. HOVER()
The hover() method takes two functions and is a
combination of the mouseenter() and mouseleave()
methods.
The first function is executed when the mouse enters the
HTML element, and the second function is executed
when the mouse leaves the HTML element:
Example
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
37. FOCUS()
The focus() method attaches an event handler function to
an HTML form field.
The function is executed when the form field gets focus:
Example
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});
38. BLUR()
The blur() method attaches an event handler function to
an HTML form field.
The function is executed when the form field loses focus:
Example
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});
39. THE ON() METHOD
The on() method attaches one or more event handlers for
the selected elements.
Attach a click event to a <p> element:
Example
$("p").on("click", function(){
$(this).hide();
});
40. JQUERY EFFECTS - HIDE AND
SHOW
jQuery hide() and show()
Example
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
42. JQUERY TOGGLE()
With jQuery, you can toggle between the hide() and
show() methods with the toggle() method.
Example
$("button").click(function(){
$("p").toggle();
});
44. JQUERY EFFECTS - FADING
With jQuery you can fade elements in and out of
visibility.
jQuery has the following fade methods:
fadeIn()
fadeOut()
fadeToggle()
fadeTo()
45. JQUERY FADEIN() METHOD
The jQuery fadeIn() method is used to fade in a hidden
element.
Syntax:
$(selector).fadeIn(speed,callback);
The optional speed parameter specifies the duration of
the effect. It can take the following values: "slow", "fast",
or milliseconds.
The optional callback parameter is a function to be
executed after the fading completes.
47. JQUERY FADEOUT() METHOD
The jQuery fadeOut() method is used to fade out a visible
element.
Syntax:
$(selector).fadeOut(speed,callback);
The optional speed parameter specifies the duration of
the effect. It can take the following values: "slow", "fast",
or milliseconds.
The optional callback parameter is a function to be
executed after the fading completes.
49. JQUERY FADETOGGLE()
METHOD
The jQuery fadeToggle() method toggles between the
fadeIn() and fadeOut() methods.
If the elements are faded out, fadeToggle() will fade them
in.
If the elements are faded in, fadeToggle() will fade them
out.
Syntax:
$(selector).fadeToggle(speed,callback);
The optional speed parameter specifies the duration of
the effect. It can take the following values: "slow", "fast",
or milliseconds.
51. JQUERY FADETO() METHOD
The jQuery fadeTo() method allows fading to a given opacity
(value between 0 and 1).
Syntax:
$(selector).fadeTo(speed,opacity,callback);
The required speed parameter specifies the duration of the
effect. It can take the following values: "slow", "fast", or
milliseconds.
The required opacity parameter in the fadeTo() method
specifies fading to a given opacity (value between 0 and 1).
The optional callback parameter is a function to be
executed after the function completes.
53. JQUERY EFFECTS - SLIDING
With jQuery you can create a sliding effect on elements.
jQuery has the following slide methods:
slideDown()
slideUp()
slideToggle()
54. JQUERY SLIDEDOWN()
METHOD
The jQuery slideDown() method is used to slide down an
element.
Syntax:
$(selector).slideDown(speed,callback);
The optional speed parameter specifies the duration of
the effect. It can take the following values: "slow", "fast",
or milliseconds.
The optional callback parameter is a function to be
executed after the sliding completes.
56. JQUERY SLIDEUP() METHOD
The jQuery slideUp() method is used to slide up an
element.
Syntax:
$(selector).slideUp(speed,callback);
The optional speed parameter specifies the duration of
the effect. It can take the following values: "slow", "fast",
or milliseconds.
The optional callback parameter is a function to be
executed after the sliding completes.
58. JQUERY SLIDETOGGLE()
METHOD
The jQuery slideToggle() method toggles between the
slideDown() and slideUp() methods.
If the elements have been slid down, slideToggle() will slide
them up.
If the elements have been slid up, slideToggle() will slide
them down.
$(selector).slideToggle(speed,callback);
The optional speed parameter can take the following values:
"slow", "fast", milliseconds.
The optional callback parameter is a function to be
executed after the sliding completes.
60. JQUERY EFFECTS -
ANIMATION
jQuery Animations - The animate() Method
The jQuery animate() method is used to create custom
animations.
Syntax:
$(selector).animate({params},speed,callback);
The required params parameter defines the CSS
properties to be animated.
The optional speed parameter specifies the duration of
the effect. It can take the following values: "slow", "fast",
or milliseconds.
The optional callback parameter is a function to be
executed after the animation completes.
63. JQUERY ANIMATE() - USING
RELATIVE VALUES
It is also possible to define relative values (the value is
then relative to the element's current value). This is done
by putting += or -= in front of the value:
Example
$("button").click(function(){
$("div").animate({
left: '250px',
height: '+=150px',
width: '+=150px'
});
});
64. JQUERY ANIMATE() - USING
PRE-DEFINED VALUES
You can even specify a property's animation value as
"show", "hide", or "toggle":
Example
$("button").click(function(){
$("div").animate({
height: 'toggle'
});
});
65. JQUERY ANIMATE() - USES
QUEUE FUNCTIONALITY
By default, jQuery comes with queue functionality for
animations.
This means that if you write multiple animate() calls after
each other, jQuery creates an "internal" queue with these
method calls. Then it runs the animate calls ONE by ONE.
66. EXAMPLE 1
$("button").click(function(){
var div = $("div");
div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, "slow");
div.animate({height: '100px', opacity: '0.4'}, "slow");
div.animate({width: '100px', opacity: '0.8'}, "slow");
});
67. JQUERY STOP ANIMATIONS
The jQuery stop() method is used to stop an animation or
effect before it is finished.
The stop() method works for all jQuery effect functions,
including sliding, fading and custom animations.
Syntax:
$(selector).stop(stopAll,goToEnd);
The optional stopAll parameter specifies whether also the
animation queue should be cleared or not. Default is false,
which means that only the active animation will be stopped,
allowing any queued animations to be performed
afterwards.
The optional goToEnd parameter specifies whether or not to
complete the current animation immediately. Default is
false.
So, by default, the stop() method kills the current animation
being performed on the selected element.
69. A callback function is executed after the current effect is
100% finished.
JavaScript statements are executed line by line. However,
with effects, the next line of code can be run even
though the effect is not finished. This can create errors.
To prevent this, you can create a callback function.
A callback function is executed after the current effect is
finished.
Typical syntax: $(selector).hide(speed,callback);
72. JQUERY - CHAINING
With jQuery, you can chain together actions/methods.
Chaining allows us to run multiple jQuery methods (on
the same element) within a single statement.
73. JQUERY METHOD CHAINING
Until now we have been writing jQuery statements one at
a time (one after the other).
However, there is a technique called chaining, that allows
us to run multiple jQuery commands, one after the other,
on the same element(s).
To chain an action, you simply append the action to the
previous action.
74. EXAMPLE
The following example chains together the css(),
slideUp(), and slideDown() methods. The "p1" element
first changes to red, then it slides up, and then it slides
down:
$("#p1").css("color", "red").slideUp(2000).slideDown(2000
);
75. When chaining, the line of code could become quite long.
However, jQuery is not very strict on the syntax; you can
format it like you want, including line breaks and
indentations.
This also works just fine:
Example
$("#p1").css("color", "red")
.slideUp(2000)
.slideDown(2000);
76. GET CONTENT AND
ATTRIBUTES
JQuery contains powerful methods for changing and
manipulating HTML elements and attributes.
DOM Manipulation:
One very important part of jQuery is the possibility to
manipulate the DOM.
JQuery comes with a bunch of DOM related methods that
make it easy to access and manipulate elements and
attributes.
77. TEXT(), HTML(), AND VAL()
Three simple, but useful, jQuery methods for DOM
manipulation are:
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
78. GET ATTRIBUTES - ATTR()
The JQuery attr() method is used to get
attribute values.
Example:
$("button").click(function(){
alert($("#w3s").attr("href"));
});
79. SET CONTENT AND
ATTRIBUTESSet Content - text(), html(), and val():
We will use the same three methods from the
previous page to set content.
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
80. A CALLBACK FUNCTION FOR
TEXT(), HTML(), AND VAL()
All of the three jQuery methods above: text(),
html(), and val(), also come with a callback
function.
The callback function has two parameters: the
index of the current element in the list of
elements selected and the original (old) value.
It return the string you wish to use as the new
value from the function.
81. SET ATTRIBUTES - ATTR()
The jQuery attr() method is also used to set/change
attribute values.
Demonstrates how to change (set) the value of the href
attribute in a link.
Example:
$("button").click(function()
{
$("#w3s").attr("href", "https://www.w3schools.com/jqu
ery");
});
The attr() method also allows you to set multiple
attributes at the same time.
82. A Callback Function for attr():
The jQuery method attr(), also come with a
callback function.
The callback function has two parameters: the
index of the current element in the list of
elements selected and the original (old)
attribute value.
Return the string you wish to use as the new
attribute value from the function.
Example:
$("button").click(function(){
$("#w3s").attr("href", function(i, origValue){
return origValue + "/jquery";
});
});
83. JQuery - Add Elements
With jQuery, it is easy to add new elements/content.
Add New HTML Content:
We will look at four jQuery methods that are used to add
new content.
append() - Inserts content at the end of the selected
elements
prepend() - Inserts content at the beginning of the
selected elements
after() - Inserts content after the selected elements
before() - Inserts content before the selected elements
84. JQUERY APPEND()
METHOD
The jQuery append() method inserts content AT THE END
of the selected HTML elements.
Example:
$("p").append("Some appended text.");
JQuery prepend() Method:
The JQuery prepend() method inserts content AT THE
BEGINNING of the selected HTML elements.
Example:
$("p").prepend("Some prepended text.");
85. Add Several New Elements With append() and
prepend():
The append() and prepend() methods can take an infinite
number of new elements as parameters.
The new elements can be generated with text/HTML
with JQuery, or with JavaScript code and DOM elements.
Example:
function appendText()
{
var txt1 = "<p>Text.</p>";
var txt2 = $("<p></p>").text("Text.");
var txt3 = document.createElement("p");
txt3.innerHTML = "Text.";
$("body").append(txt1, txt2, txt3);
}
86. JQuery after() and before() Methods:
The jQuery after() method inserts content AFTER the
selected HTML elements.
The jQuery before() method inserts content BEFORE the
selected HTML elements.
Example:
$("img").after("Some text after");
$("img").before("Some text before");
87. Add Several New Elements With after() and before():
The after() and before() methods can take an infinite
number of new elements as parameters.
The new elements can be generated with text/HTML with
jQuery, or with JavaScript code and DOM elements.
Example:
function afterText()
{
var txt1 = "<b>I </b>";
var txt2 = $("<i></i>").text("love ");
var txt3 = document.createElement("b");
txt3.innerHTML = "jQuery!";
$("img").after(txt1, txt2, txt3);
<img>
}
88. JQuery - Remove Elements:
With jQuery, it is easy to remove existing HTML
elements.
Remove Elements/Content:
To remove elements and content, there are mainly two
jQuery methods.
remove() - Removes the selected element (and its child
elements)
empty() - Removes the child elements from the selected
element
JQuery remove() Method
The JQuery remove() method removes the selected
element(s) and its child elements.
Example:
$("#div1").remove();
89. JQUERY EMPTY() METHOD:
The JQuery empty() method removes the child elements
of the selected element(s).
Example:
$("#div1").empty();
Filter the Elements to be Removed:
The jQuery remove() method also accepts one parameter,
which allows you to filter the elements to be removed.
The parameter can be any of the jQuery selector
syntaxes.
Example:
$("p").remove(".test");
90. JQUERY - GET AND SET CSS CLASSES
With JQuery, it is easy to manipulate the CSS of elements.
JQuery Manipulating CSS:
JQuery has several methods for CSS manipulation.
addClass() - Adds one or more classes to the selected
elements
removeClass() - Removes one or more classes from the
selected elements
toggleClass() - Toggles between adding/removing
classes from the selected elements
css() - Sets or returns the style attribute
91. JQUERY ADDCLASS() METHOD
It shows how to add class attributes to different
elements. Of course you can select multiple elements,
when adding classes.
Example:
$("button").click(function(){
$("h1, h2, p").addClass("blue");
$("div").addClass("important");
});
We can also specify multiple classes within the addClass()
method.
Example:
$("button").click(function(){
$("#div1").addClass("important blue");
});
92. JQuery removeClass() Method:
It shows how to remove a specific class attribute from
different elements.
Example:
$("button").click(function()
{
$("h1, h2, p").removeClass("blue");
});
JQuery toggleClass() Method:
It show how to use the JQuery toggleClass() method. This
method toggles between adding/removing classes from
the selected elements.
Example:
$("button").click(function(){
$("h1, h2, p").toggleClass("blue");
});
93. JQuery css() Method:
The css() method sets or returns one or more style
properties for the selected elements.
Return a CSS Property:
To return the value of a specified CSS property, use
the following syntax:
css("propertyname");
Example:
$("p").css("background-color");
Set a CSS Property:
To set a specified CSS property, use the following syntax:
Syntax:
css("propertyname","value");
94. Set Multiple CSS Properties:
To set multiple CSS properties, use the following syntax:
Syntax:
css({"propertyname":"value","propertyname":"value",...});
Example:
$("p").css({"background-color": "yellow", "font-
size": "200%"});
95. JQuery - Dimensions
JQuery Dimension Methods:
JQuery has several important methods for working with
dimensions:
width()
height()
innerWidth()
innerHeight()
outerWidth()
outerHeight()
96. JQuery width() and height() Methods:
The width() method sets or returns the width of an
element (excludes padding, border and margin).
The height() method sets or returns the height of an
element (excludes padding, border and margin).
Example:
$("button").click(function()
{
var txt = "";
txt += "Width: " + $("#div1").width() + "</br>";
txt += "Height: " + $("#div1").height();
$("#div1").html(txt);
});
97. JQuery innerWidth() and innerHeight() Methods:
The innerWidth() method returns the width of an element
(includes padding).
The innerHeight() method returns the height of an
element (includes padding).
Example:
$("button").click(function()
{
var txt = "";
txt += "Inner width: " + $("#div1").innerWidth()
+ "</br>";
txt += "Inner height: " + $("#div1").innerHeight();
$("#div1").html(txt);
});
98. JQuery outerWidth() and outerHeight() Methods:
The outerWidth() method returns the width of an element
(includes padding and border).
The outerHeight() method returns the height of an element
(includes padding and border).
Example:
$("button").click(function()
{
var txt = "";
txt += "Outer width: " + $("#div1").outerWidth()
+ "</br>";
txt += "Outer height: " + $("#div1").outerHeight();
$("#div1").html(txt);
});
Note: The outerWidth(true) method returns the width of an
element (includes padding, border, and margin).
The outerHeight(true) method returns the height of an
element (includes padding, border, and margin).
99. JQuery More width() and height():
It returns the width and height of the document (the
HTML document) and window (the browser viewport).
Example:
$("button").click(function()
{
var txt = "";
txt += "Document width/height: " +
$(document).width();
txt += "x" + $(document).height() + "n";
txt += "Window width/height: " + $(window).width();
txt += "x" + $(window).height();
alert(txt);
});
100. JQUERY TRAVERSING
Traversing:
JQuery traversing, which means "move through", are used
to "find" HTML elements based on their relation to other
elements.
Start with one selection and move through that selection
until you reach the elements you desire.
The image below illustrates a family tree.
With JQuery traversing, We can easily move up, down
and sideways in the family tree, starting from the
selected element.
This movement is called traversing - or moving through
- the DOM.
101. An ancestor is a parent, grandparent, great-grandparent,
and so on.
A descendant is a child, grandchild, great-grandchild,
and so on.
Siblings share the same parent.
102. Traversing the DOM:
JQuery provides a variety of methods that
allows us to traverse the DOM.
The largest category of traversal methods are
tree-traversal.
The next chapters will show us how to travel
up, down and sideways in the DOM tree.
103. JQUERY TRAVERSING - ANCESTORS:
An ancestor is a parent, grandparent, great-grandparent,
and so on.
With jQuery you can traverse up the DOM tree to find
ancestors of an element.
Traversing Up the DOM Tree
Three useful JQuery methods for traversing up the DOM
tree
parent()
parents()
parentsUntil()
104. JQuery parent() Method:
The parent() method returns the direct parent element of
the selected element.
This method only traverse a single level up the DOM
tree.
Example:
$(document).ready(function()
{
$("span").parent();
});
It returns the direct parent element of each <span>
elements
105. JQuery parents() Method:
The parents() method returns all ancestor elements of
the selected element, all the way up to the document's
root element (<html>).
Example:
$(document).ready(function()
{
$("span").parents();
});
Example returns all ancestors of all <span> elements.
We can also use an optional parameter to filter the
search for ancestors.
Example:
$(document).ready(function(){
$("span").parents("ul");
});
Example returns all ancestors of all <span> elements
that are <ul> elements
106. JQuery parentsUntil() Method:
The parentsUntil() method returns all ancestor
elements between two given arguments.
Example:
$(document).ready(function()
{
$("span").parentsUntil("div");
});
Example returns all ancestor elements
between a <span> and a <div> element
107. JQuery Traversing - Descendants:
A descendant is a child, grandchild, great-
grandchild, and so on.
With jQuery you can traverse down the DOM tree to
find descendants of an element.
Traversing Down the DOM Tree:
Two useful jQuery methods for traversing down the
DOM tree are:
children()
find()
108. children() Method:
The children() method returns all direct children of
the selected element.
This method only traverse a single level down the
DOM tree.
Example:
$(document).ready(function()
{
$("div").children();
});
109. JQuery find() Method:
The find() method returns descendant elements of
the selected element, all the way down to the last
descendant.
Example
$(document).ready(function()
{
$("div").find("span");
});
110. JQuery Traversing - Siblings:
Siblings share the same parent.
With jQuery you can traverse sideways in the DOM tree
to find siblings of an element.
Traversing Sideways in The DOM Tree
There are many useful jQuery methods for traversing
sideways in the DOM tree:
osiblings()
onext()
onextAll()
onextUntil()
oprev()
oprevAll()
oprevUntil()
111. JQuery siblings() Method:
The siblings() method returns all sibling elements of the
selected element.
You can also use an optional parameter to filter the
search for siblings.
It returns all sibling elements.
Example:
$(document).ready(function()
{
$("h2").siblings();
});
112. JQuery next() Method:
The next() method returns the next sibling element of
the selected element.
It returns the next sibling of <h2>
Example:
$(document).ready(function(){
$("h2").next();
});
113. JQuery nextAll() Method:
The nextAll() method returns all next sibling
elements of the selected element.
Example:
$(document).ready(function()
{
$("h2").nextAll();
});
114. JQuery nextUntil() Method:
The nextUntil() method returns all next sibling
elements between two given arguments.
Example:
$(document).ready(function()
{
$("h2").nextUntil("h6");
});
115. JQuery prev(), prevAll() & prevUntil() Methods:
The prev(), prevAll() and prevUntil() methods work
just like the methods above but with reverse
functionality.
They return previous sibling elements (traverse
backwards along sibling elements in the DOM tree,
instead of forward).
116. JQUERY TRAVERSING -
FILTERING
Narrow Down The Search For Elements
The three most basic filtering methods are
first(), last() and eq(), which allow you to select
a specific element based on its position in a
group of elements.
Other filtering methods, like filter() and not()
allow you to select elements that match, or do
not match, a certain criteria.
117. JQUERY FIRST() METHOD
The first() method returns the first element of the
selected elements.
The following example selects the first <p> element
inside the first <div> element:
Example
$(document).ready(function(){
$("div p").first();
});
118. JQUERY LAST() METHOD
The last() method returns the last element of the selected
elements.
The following example selects the last <p> element
inside the last <div> element:
Example
$(document).ready(function(){
$("div p").last();
});
119. JQUERY EQ() METHOD
The eq() method returns an element with a
specific index number of the selected elements.
The index numbers start at 0, so the first
element will have the index number 0 and not
1. The following example selects the second
<p> element (index number 1):
Example
$(document).ready(function(){
$("p").eq(1);
});
120. JQUERY FILTER() METHOD
The filter() method lets you specify a criteria.
Elements that do not match the criteria are
removed from the selection, and those that
match will be returned.
The following example returns all <p>
elements with class name "intro":
Example
$(document).ready(function(){
$("p").filter(".intro");
});
122. JQUERY NOT() METHOD
The not() method returns all elements that do not match
the criteria.
Tip: The not() method is the opposite of filter().
The following example returns all <p> elements that do
not have class name "intro":
Example
$(document).ready(function(){
$("p").not(".intro");
});
125. TRAVERSAL METHODS
List of all traversal methods on the jQuery API site
http://api.jquery.com/category/traversing
126. CONTEXT
$('selector', 'context')
Different from "or" selector – $('selector1, selector2')
Same as $('context').find('selector')
Not worth using; too confusing.
.add()
.andSelf()
.end()
128. CHAINING
JavaScript has chaining built in.
'swap this text'.replace(/w/, 'n').replace(/this/,'that');
'616-555-1212'.split('-').join('.');
jQuery takes advantage of this concept by having almost
all methods return the jQuery object.
132. var lis = $('.container li:first')
.addClass('first-li')
.next()
.addClass('second-li')
.end()
.nextAll()
.addClass('not-first-li')
.end(); // unnecessary; added for symmetry
CHAINING
JavaScript ignores white space, so use it to your advantage.
134. $('li').each(function() {
console.log( this ); // DOM element
console.log( $(this) );
});
THIS KEYWORD
Refers to the current object
jQuery sets this to matched elements in the jQuery object.
135. var $listItems = $('li');
var numItems = $listItems.length
//no need for length check
$listItems.addClass('pretty');
if (numItems) {
// do something with other elements
}
TIPS
Store selectors used more than once in variables
Use length property to check existence
...but often no need for the check
139. THE BASICS
Strings: textual content. wrapped in quotation marks
(single or double).
'hello, my name is Karl'
"hello, my name is Karl"
Numbers: integer (2) or floating point (2.4) or octal (012)
or hexadecimal (0xff) or exponent literal (1e+2)
Booleans: true or false
In JavaScript, you can work with the following things:
140. THE BASICS
Arrays: simple lists. indexed starting with 0
['Karl', 'Sara', 'Ben', 'Lucia']
['Karl', 2, 55]
[ ['Karl', 'Sara'], ['Ben', 'Lucia']]
Objects: lists of key, value pairs
{firstName: 'Karl', lastName: 'Swedberg'}
{parents: ['Karl', 'Sara'], kids: ['Ben', 'Lucia']}
In JavaScript, you can work with the following things:
141. VARIABLES
Always declare your variables!
If you don't, they will be placed in the
global scope
(more about that later).
bad: myName = 'Karl';
good: var myName = 'Karl';
still good: var myName = 'Karl';
// more stuff
myName = 'Joe';
143. LOOPS
Loops iterate through a list of some
kind.
A common pattern in JavaScript is
to build a list, or collection, and
then do something with each item
in that list.
144. LOOPS
CSS uses implicit iteration.
div { color: red; } /* applies to ALL divs */
JavaScript relies on explicit iteration.
Must explicitly loop through each div
jQuery allows for both (because it does
the looping for you)
145. LOOPS
The two most common loops...
for loops — for general-purpose iteration.
Used with arrays or array-like objects)
for-in loops — used with arrays or objects (but
don't use with arrays)
The other two are...
while loops
do-while loops
146. for (initial value; condition; increment) {
// code block
}
FOR LOOPS
three statements and a code block
1.initial value
2.condition
3.increment
147. FOR LOOPS
for (var i = 0; i < 3; i++) {
alert(i+1);
}
This is your variable,
so it can be anything!
(but developers often
use “i”)
148. FOR LOOPS
var divs =
document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
// do something with each div
individually
divs[i].style.color = 'red';
}
149. FOR LOOPS
var divs = document.getElementsByTagName('div');
// better to store length in variable first
var divCount = divs.length
for (var i = 0; i < divCount; i++) {
// do something with each div individually
divs[i].style.color = 'red';}
150. FOR LOOPS
var divs = document.getElementsByTagName('div');
// can store it directly in the initializer
for (var i=0, divCount=divs.length; i < divCount;
i++) {
// do something with each div individually
divs[i].style.color = 'red';
}
151. FOR-IN LOOPS
var family = {
dad: 'Karl',
mom: 'Sara',
son: 'Benjamin',
daughter: 'Lucia'
}
for (var person in family) {
alert('The ' + person + ' is ' + family[person]);
}
This is your variable,
so it can be anything!
152. WHILE AND DO-WHILE
var i = 1;
while (i < 4) {
alert(i);
i++;
}
var j = 1; // code block always executed at
least once
do {
alert(j);
j++;
} while (j < 4)
153. THE BASICS:
FUNCTIONS
Functions allow you to define a block of code, name that
block, and then call it later as many times as you want.
function myFunction( ) { /* code goes here */ } // defining
myFunction( ) // calling the function myFunction
You can define functions with parameters
function myFunction(param1, param2 ) { /* code goes here
*/ }
You can call functions with arguments:
myFunction('one', 'two')
In JavaScript, you can also work with functions:
154. FUNCTIONS
// define a function
function doSomething() {
alert('I am something');
}
// call the function
doSomething();
155. FUNCTIONS
// define a function
function sumThing(a, b) {
return a + b;
}
// call the function
alert( sumThing(1, 2) );
156. FUNCTIONS
// define a function
function sumThing(a, b) {
return a + b;
}
var mySum = sumThing(1, 2);
// call the function
alert( mySum );
157. THE ARGUMENTS
OBJECT
Every function has an arguments object
a collection of the arguments passed to the function
when it is called
an "array-like object" in that it is indexed and has a
length property but can't attach array methods to it
can be looped through
allows for variable number of arguments
158. FUNCTIONS
// call the function
function logThing() {
for (var i=0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
// call the function
logThing(1, 2, 'three');
/* prints to the console: >> 1 >> 2 >> three
*/
159. EXERCISE
Convert the sumThing function to allow for variable
number of arguments.
function sumThing(a, b) {
return a + b;
}
Use a for loop to loop through the arguments object,
adding to a "sum" variable with each iteration.
After the loop, return sum.
160. (SIMPLE) SOLUTION
// define a function
function sumThing() {
var sum = 0,
countArgs = arguments.length;
for (var i = 0; i < countArgs; i++) {
sum += arguments[i];
}
return sum;
}
// call the function
console.log( sumThing(1, 2, 4 ) );
161. function multiple(n) {
function f(x) {
return x * n;
}
return f;
}
var triple = multiple(3);
var quadruple = multiple(4);
console.log( triple(5) ); // 15
console.log( quadruple(5) ); // 20
console.log( multiple(4)(5) ); // 20
RETURNING FUNCTIONS
Functions can return other functions
162. NAMED VS. ANONYMOUS
FUNCTIONS
Named:
function foo() { } // function declaration
var foo = function foo() { }; // function
expression
Anonymous:
var foo = function() { }; // function expression
163. ANONYMOUS FUNCTIONS
Prevalent in jQuery
Good for creating closures
Used as "callback" functions
Can be used as object properties (methods)
let’s take a look ...
165. function() {
// variables are defined within this scope
// avoid name collisions
}
ANONYMOUS FUNCTIONS
Good for creating closures
166. (function() {
// variables are defined within this scope
// avoid name collisions
})();
ANONYMOUS FUNCTIONS
Good for creating closures
Can be defined and then immediately invoked:
“immediately invoked function expression,” ( a.k.a. IIFE;
pronounced “iffy”)
167. (function($) { // "$" is the function's param
})(jQuery); // function is called with "jQuery"
ANONYMOUS FUNCTIONS
Good for creating closures
Used by plugins to keep jQuery safe.
168. $('p').slideDown('slow', function() {
// code in here is not executed
// until after the slideDown is
finished
// jQuery calls the code in here when
effect ends
});
ANONYMOUS FUNCTIONS
Used as "callback" functions
169. OBJECTS
Objects are objects : { }
Arrays are objects : [ ]
even Functions are objects : function( ) { }
jQuery is an object
Numbers, strings, and booleans (true/false) are primitive
data types, but they have object wrappers.
In JavaScript, everything is an object. Well, almost everything.
170. GLOBAL OBJECT
location
parseInt(); parseFloat()
isNaN()
encodeURI(); decodeURI()
setTimeout(); clearTimeout()
setInterval(); clearInterval()
In the browser environment, the global object is window
It collects all functions and variables that are global in scope.
Usually implied.
Comes with some useful properties and methods:
171. DATE OBJECT
var now = new Date(); // current date and time
var then = new Date('08/12/2000 14:00');
console.log( then.getTime() ); // 966103200000
console.log( then.toString() );
// Sat Aug 12 2000 14:00:00 GMT-0400 (EDT)
console.log( then.getMonth() ); // 7 !!!!
173. CREATING A REGEXP
Object constructor
var re = new RegExp('hello');
Regular expression literal
var re = /hello/;
174. USING A REGEXP
var text = 'The quick brown fox';
var re = new RegExp('quick');
console.log( re.test(text) ); // true
console.log( /brown/.test(text) ); // true
console.log( /red/.test(text) ); // false
175. REGEXP SYNTAX
Most characters (incl. all alphanumerics) represent
themselves
Special characters can be escaped with a backslash ()
176. CHARACTER CLASSES
/t.p/ matches 'tap' and 'tip' and 'top'
/t[ai]p/ matches 'tap' and 'tip', not 'top'
/t[a-k]p/ matches 'tap' and 'tip', not 'top'
/t[^m-z]p/ matches 'tap' and 'tip', not 'top'
182. STRING REPLACEMENT
var str =
'The quick brown fox jumps over the lazy dog.';
console.log(str.replace(/[aeiou]/, '*'));
// Th* quick brown fox jumps over the lazy dog.
183. REGEXP FLAGS
Placed after closing / character
Global (g): find as many as possible
Case insensitive (i)
Multiline (m): ^ and $ work with newlines
184. STRING REPLACEMENT
var str =
'The quick brown fox jumps over the lazy dog.';
console.log(str.replace(/[aeiou]/g, '*'));
// Th* q**ck br*wn f*x j*mps *v*r th* l*zy d*g.
console.log(str.replace(/the/gi, 'a'));
// a quick brown fox jumps over a lazy dog.
185. BACKREFERENCES
var str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.replace(/r(.)/g, '$1x'));
// The quick boxwn fox jumps ove xthe lazy dog.
186. REPLACEMENT FUNCTIONS
var str = 'Kill 5+9 birds with 2+5 stones.';
function add(match, first, second) {
return parseInt(first, 10) + parseInt(second, 10);
}
str = str.replace(/([0-9]+)+([0-9]+)/g, add);
console.log(str);
// Kill 14 birds with 7 stones.
187. EXERCISES
Write a function that uppercases all the
vowels in a string.
Write a function that strips the angle
brackets from around any HTML tags in a
string.
188. GREEDINESS
Repeat operators usually match as much
of the string as possible; they are greedy
JavaScript supports reluctant repetition
as well
Append ? to the repeat operator
189. AND MUCH MORE
JavaScript supports most Perl
regular expression extensions
POSIX character classes
Unicode character escapes
Look-ahead assertions
190. MATH OBJECT
Not a constructor, a singleton
Gathers useful methods and properties
Math.PI
Math.abs(), Math.sin(), Math.pow(),
Math.random(),
Math.max(), Math.min()
Math.round(), Math.floor(), Math.ceil()
191. CSS:
h3 {
font-size: 1.2em;
line-height: 1;
}
JS:
var h3 = {
fontSize: '1.2em',
'line-height': 1
};
CSS TIP
Object literal notation looks a lot like CSS style rule
notation!
192. var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
OBJECT LITERALS
person is the object
firstName and lastName are properties
hello is a method (a property that is a function)
193. var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
},
interests: {
athletic: ['racquetball', 'karate', 'running'],
musical: ['rock', 'folk', 'jazz', 'classical']
}
};
OBJECT LITERALS
interests is a property and an object
194. OBJECT LITERALS
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
} // ⬅ notice, no comma here!
};
195. OBJECT LITERALS
“DOT” NOTATION
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
// "dot" notation
person.firstName; // 'Karl'
person.lastName; // 'Swedberg'
person.hello() // 'Hello, my name is Karl Swedberg'
196. OBJECT LITERALS
ARRAY NOTATION
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
// array notation
person['firstName']; // 'Karl'
person['lastName']; // 'Swedberg'
person['hello']() // 'Hello, my name is Karl Swedberg'
197. var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
},
interests: {
athletic: ['racquetball', 'karate', 'running'],
musical: ['rock', 'folk', 'jazz', 'classical']
}
};
// person['interests']['musical'][1] == ??
// == person.interests.musical[1]
OBJECT LITERALS
198. OBJECT LITERALS
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
person.firstName = 'Karl';
var prop = 'firstName';
person[ prop ]; // 'Karl'
prop = 'lastName';
person[ prop ]; // 'Swedberg'
199. OBJECT LITERALS
var blah;
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
for (var el in person) {
blah = typeof person[el] == 'function' ?
person[el]() :
person[el];
console.log( blah );
}
200. doSomething({
speed: 'fast',
height: 500,
width: 200,
somethingElse: 'yes'
});
doSomething({width: 300});
OBJECT LITERALS
Great as function arguments
single argument allows flexibility when calling the function
205. JSON
JAVASCRIPT OBJECT NOTATION
a data interchange format. In other words, a format for
passing data back and forth
“discovered” and popularized by Douglas Crockford
a subset of JavaScript Object Literal Notation
a tree-like structure of object(s) and/or array(s)
no functions
all strings, including object keys, take double quotes