14
Jan

jQuery Full Course | jQuery Tutorial For Beginners | jQuery Certification Training | Edureka


Hi guys welcome to this comprehensive
session on jQuery so in this session we’ll cover the following topics that
you can see on the screen so we’ll start this session by understanding the
introduction to jQuery and then we’ll understand the Dom manipulation and
jQuery effect once you understand these concepts we’ll go through the jQuery
forms and events and finally end this session with jQuery AJAX and utilities
so today we have a special guest one who’s gonna take the session forward so
what do you want hello everyone welcome to 80 acres on jQuery UI development I
will be your instructor for this course my name is Varun and before we begin I
would like to share a short introduction about myself I’ve been doing development
for about six years now and I have done development in several languages
these include python, JavaScript, PHP Ruby, Java, Android and for the past two
years or so I’ve also been working on angular 1.X JavaScript continues to
be one of my favorite go-to languages for its ease of use and jQuery is
something that I used extensively in the past and I believe that it’s a very very
very important stepping stone when you’re learning about front-end
development it is one of the key stepping stones that you need to I think
every developer needs to know a little bit of at least before they go on to
things like angularjs or react.js and vue.js so that’s about me right so just
a quick refresher on what HTML CSS and JavaScript is for so hTML is basically
the structure of your website in terms of the architecture ok this is the same
that ok I want a box here where I want a round shape here and this is the layout
write CSS ads any sort of styling to that structure whether it’s from color
or shadowing or font size or font weight multiple multiple things JavaScript
however brings your website to life right so of course you can make a pretty
HTML and CSS web page but then if it doesn’t do anything
and by doing I mean when you click on a button or when you hover over something
or some yes it doesn’t really do anything it
kind of becomes boring afterward right I mean on Facebook how interesting would
Facebook me if you could not really like anything you could just read information
JavaScript adds interactivity or to your webpages how you might have experienced
that a little bit already by if you have done JavaScript but otherwise you going
to see now how it does that and what are the ways in terms of how you can add
interrupt it with interactivity to your web page and as as the image goes right
hTML is so structure CSS is for presentation and javascript is for
behavior so let’s look at the basic Dom structure so basic drawn structure this
is just a simple HTML document here and they have laid it out in a tree sort of
pattern okay there is the document it is the parent of everything else the
document tag within the document tag then you have HTML tag which further
contains head and body and then head contains title and try to contain some
text over here if you if you look at this right and then you have h1 tag
which contains some text and then you have the P tag which is which contains
some text the Dom really refers to so so whenever you’re writing HTML what is
really happening is that you write certain directions to a browser so a
browser is a software right through writing HTML you are writing certain
directions to the browser that hey paint my web page in a certain way so it’s
like if you had a friend and he had a canvas that canvas and that friend
together are the browser and you as a developer are the person who is
instructing this browser or person and you’re telling this person hey draw a
box for me make it this wide make it like this make it have this shadow
effect print or print or display a message like box one over it the font
size the font weight multiple multiple thing right or if it’s a document like
let’s suppose you’re dictating a document to somebody okay the heading
should be jQuery training that starts with the subheading jQuery intro then
start with the paragraphs plan your jQuery training now so
it’s that is sort of the way that the browsers work this HTML is essentially
directions they are essentially directions to the browser okay what the
browser does is that it takes those directions and creates something called
as add-ons a document object model artifact now why does it create a dog
because it needs to apply the styles that you have provided from the CSS it
needs to do several things to it so it converts it into something called as a
dom and makes it available to you and to itself for manipulation and a large part
of JavaScript or jQuery has to deal with Dom manipulation and you’re going to
figure that out as you go along right so then it comes to Dom manipulation right
if you look at this example some of you might be familiar with this right so
let’s talk about this particular line let’s suppose that there is a div tag
with the ID results this particular line basically gets that element gets that
Dom element to you in this variable in this JavaScript variable and the
following lines are setting the HTML inside it so basically you are setting
HTML or you’re setting text inside an HTML using javascript now that’s a very
very powerful concept right right there that you can deliver of a page to a user
with a certain look and feel and then based on how the user decides to
interact with it you will make changes to that web page you can literally
change this entire web page right there and then because you have JavaScript
helping you out because it has access it can read that HTML document that Dom it
can read the Dom and pick out the nodes in the Dom so think of these as nodes
and think of jQuery having access to each of these nodes and having the
ability to modify each of these nodes whether it is the content of the node or
it is something else that it can do to a node now one thing about the Dom is that
every browser behaves a little differently
so if you ever felt that your website doesn’t look
the same on Chrome or vs. Mozilla versus Internet Explorer versus opera about
Safari and I’m sure you must have experienced this with even very very
good websites like they tend to differ quite a bit depending on how careful the
developers were so the reason is that it’s not broken it’s just that every
browser behaves differently so it’s like this consider each of the browser as a
person right this is train day this is friend B this
is a friend see you are giving directions to paint the dom so you want
something called as a document to be painted or printed on a canvas and
you’re giving instructions to each browser but each browser behaves
differently each bit like like a person the browser behaves differently to
instructions now 90 to 95 percent of the behavior is similar but that 10% 15%
depending on what kind of instructions you are giving might change so the
websites don’t look massively different but they are still a little different
right so that comes from who developed that browser what did they want to build
it for what is the main purpose so Internet Explorer for example is built
primarily for security it is supposed to be very secure chrome is built for
something else Firefox is built for speed Safari is
built for something else Opera it for something else and based on those
decisions sometimes these behaviors change where they might not react to a
CSS property or they might not perceive a certain way in a certain way in a
certain directive in a certain way so this is a problem this is a huge problem
for developers who have to build quickly and have they have to build websites
which would sort of at least 90 to 99 percent of the time behave in a similar
way across browsers because if you were to build four different browsers it or
if you were to write separate cool say doing the same thing for different
browsers it would be just too much work and developers are supposed to be lazy
right so jQuery helps us out jQuery really had freely helps us out so think
of jQuery like on manager okay think of jQuery like a
manager who knows each of the workers so if if these are my friends
he knows the behavior of each and every friend he knows Firefox requires more
directions than Chrome or Chrome is a bit slower than Internet Explorer or
Internet Explorer needs to be given the instructions slowly now these are not
the actual differences but I’m just giving you an example now as a manager
jQuery knows how to deal with the different behavior of different browsers
so it eliminates the need for us to write code specific to browsers instead
it takes care of it for us that is the first and most fundamental reason why
jQuery is so so popular then it removes a dependency to write code for each and
every individual browser makes it very very easy for people like you and me to
build websites really really quickly okay so what is jQuery then so jQuery is
essentially a JavaScript library so a tester JavaScript please don’t be
confused about this I see people early on being a little confused in terms of
what is the difference between javascript and jquery javascript is a
language jQuery is a library built using JavaScript so jQuery fundamentally is
nothing but a lot of JavaScript code that has been written by developers who
are very very experienced who have 20 to 25 years of experience developing and
programming and so on and so forth so jQuery is just a library now it was
first released in 2006 it’s one of the most popular libraries with cross
browser support it is lightweight lightweight being that the file isn’t
too much it improves developer efficiency of course easy to learn
because it relies on a lot of CSS based syntax we’ll come across this soon so
let’s move ahead now the next question is why jQuery we I have already answered
this a little bit but let me still go through it so jQuery is a JavaScript
library designed to simplify the client-side scripting naturally
of the syntax being similar to CSS cross browser support it helps in creating
dynamic web pages now dynamic in terms of whenever you may are able to
manipulate the Dom that is what adds a dynamic nature to your web page and you
have web application so that is one of the fundamentals again that it creates
dynamic web pages which respond to user input it is intuitive and easy to learn
you’ll figure that as we go along it integrates with ID so IDs have
out-of-the-box support for it it helps in pages loading faster so because the
size is small the download time of the library and itself is small which helps
out so generally when you find websites to be slow either it’s your internet
connection and if that’s not the case then the website is heavy heavy being
that the size of the code that you’re downloading to runs the website is a lot
next is that it helps in creating animated pages like flash so before
JavaScript or jQuery or even jQuery became really popular one of the typical
ways to animate a web page was using flash however that means that is a
front-end developer you have to do an HTML CSS JavaScript and flash further
flash is not I think it would be sort of sufficient to say that it’s not the most
elegant of things to deal with when it comes to browsers okay a lot of problems
across browsers and across always as well so what happens is that jQuery
because it’s so easy to use there are so many functions already built in it
provides us with a lot of functionality to create animation which is similar to
flash but without using flash so in terms of you learning newer things it
reduces the number of newer things that you have to learn you don’t have to
learn – and you’re still able to create beautiful animations using jQuery which
is also a part of a dynamic web page right of a page which can sort of
animate based on user input or based on certain sections being loaded and so on
so HTML document type it informs the browser word document type it is and
again it has to do with the in interpretation of the document so again
the document the HTML document just contains directions to paint a web page
and the doctype basically tells the browser which version of directions
these are and so it is very important till HTML for this was the way that he
would mention the HTML document type and from html5 is just very simple you just
type this and that’s it this would be sufficient
now CSS selectors so I’m pretty sure that you guys must have come across this
by now there are various ways so whenever you give directions in terms of
hey I want the box to be your Fred color or I want the font to be 14 pixel or I
want to divide up the page and columns of 20% 20% and 40% right you write that
code as CSS but then how do you tell CSS how do you link the HTML and CSS
together in terms of what style is to be applied on what element that happens
through selectors now there are multiple ways to select or identify attack so
imagine it in this way that there are eight boxes that you’re telling your
friend tube that you told your friend to paint on the canvas now you want one of
the boxes to be of red color naturally the friend will ask hey which box now if
the boxes were numbered that they were identified as 1 2 3 4 5 6 7 8 you would
tell your friend here box number three needs to be of red color now when you’re
doing this this is an identifier and selector is I think a synonym you can
consider it as a synonym for an identifier so there are various ways to
identify a HTML tag one of them is the tag name in itself that is a P tag or a
div tag or a span tag and these are then universally applied so if I apply a span
tag with font size of 14 pixel that will be applied across anywhere in my HTML
document that I use a span tag then there are ID selectors which you set by
setting the ID on the HTML then you can of course said this class
selector as well now tag ID in class tend to be the most popular ones but
then there are more there are a lot of ways in which you can set selectors
there are pseudo-class selectors there are selectors based on
relationships that is the parent-child relationship then there are attribute
based selectors and then there are multiple selectors as well so for now I
think he can focus on the top three that is tag ID in class but I think even
selectors based on relationships tend to be commonly used as compared to the
other ones right so the jQuery object if you have studied
JavaScript you must have studied the object so just a quick refresher in case
somebody has forgotten let’s say I open my localhost
okay so this is an empty web page right now but just to quickly show you what I
mean is that this is an object in JavaScript right curly braces open and
curly braces closed and it essentially contains key value pairs so if I had to
count the number of fruits I could store it like this and then if I do a dot
Apple it’s print one here on banana I put paint two and a dot guava to print
three so similarly what you have is something
called as a jQuery object now there are two ways to use the jQuery object one is
the dollar symbol and the other one is jQuery written in this particular casing
that is j-cap a small and cue capital and the rest of them small again you can
use either it is fine if you use dollar or if you jQuery but a lot of times the
examples that you will find on the internet will be using dollar so I think
for those course you will stick to dollar now dollar is essentially a
function okay you need to really look at it like JavaScript syntax so it’s dollar
is nothing but for you of variable so if I was to show it to you again you can
consider it like this where dollar is equal to this right now
I can say dollar dot a equal to three and if I do add a print dollar then it
is an object so dollar is a valid identifier or a variable name in
JavaScript in javascript in general but what jQuery does is that it adopted the
dollar as a symbol for itself that all jQuery needs to be accessed through the
dollar and if you look at it it’s not just a variable actually it’s a function
jquery Fisker these parentheses right if so in JavaScript functions are called by
the parentheses the clew opening of the closing of the brackets and then code
inside it so this is essentially the jquery function which
a lot of things inside it a lot of things as we will discover but you need
really need to visualize it in that particular way that I’m just calling a
function that’s it okay so a jQuery object is like an array
which contains zero or more indexes it also contains object methods like length
context and selector so I think as you go along we will figure out how all of
this is true so it’s a jQuery object contains a lot of things right and I
will just show it to you in a few moments what all it contains but keep in
mind that it is nothing but JavaScript at the end of the day so we are not
going to lose sight of the fundamentals very very important ok so some ID so
jQuery so I’m going to be using atom there is sublime text again one of the
very good ones lightweight but there is Dreamweaver you can also use it in the
browser console like I was just demonstrating there are only editor such
as jsfiddle J’s pin cloud 9 and then there are debuggers so I just use a
Chrome web inspector in far in Mozilla Firefox it is a Firebug and you can use
Ito depending on what you’re familiar with what you have installed all of them
are are good right so jQuery CDN and installation so there are two ways of
installing jQuery in the web project one is to download jQuery and half the file
like just like a javascript file stored on your on your laptop or in your
project and give the path to it so that is what I have done I have the jQuery
you are gs5 here if you can see this is a lot of scary JavaScript don’t be
confused by it no you don’t have to read through all of this but I just included
it like this so I just added it it’s over here it will find it and I will be
able to use it ok and the other way is through the CDN which is called as a
content delivery network so just a small node I’ll not go into the day
of CDN but CDN are basically hosted by big companies such as CloudFlare such as
Google’s it is Amazon jQuery in itself might have its own CDN which are
basically localized servers so servers which are close to your specific
location respond to your requests the benefit of a CDN is that of course
because the server is physically close to you physically meaning that it’s not
sitting in the US if you are in India it’s sitting in Singapore but if you are
in u.s. it’s not serving your file from India or UK or Europe it is serving your
files from us itself so physical proximity plays a role of course in
transfer rate as well as the fact that the file version is being maintained and
you don’t have to maintain a copy of the file on your own machine that also plays
a role then there are certain other benefits in weight being a standard
files on and so forth forces you choosing it from you know
something that poor developer downloaded to you I sure that it is the original
jQuery and it’s not been modified it’s not even messed around with so because
if you think about this right there is this file I might accidentally edit it I
just edited it now something might break if I am another developers on this
project but if you’re downloading it from the CD and I can’t really
accidentally may change something so that is why the Sirian helps out but if
you’re developing a local I usually prefer local being if you just in
development mode I usually prefer having the files on my machine because that’s
much faster because it’s just serving the files from my machine to my machine
and I don’t have to wait for it to download from a server so development I
would suggest that govind downloading the file ok so before we start with this
let me show you something now notice that I’ve already loaded the JavaScript
file the jQuery file sorry and I’m doing a console dot log of dollar I have not
defined dollar anywhere I like the browser okay and I’m going to reload
this page to reload this page on my browser I’m
going to just get rid of this and if you’d notice it has jQuery HTML 936 line
36 and has done a console dot log it has returned a function so jQuery dollar is
a is a function essentially which can be a little head spinning but in JavaScript
even functions or objects okay even functions are objects so when when it
said that dollar is an object it is correct and when it says dollar is a
function is correct because functions are also objects in JavaScript now if I
do jQuery I’ll get the result as the same function
and for comparison sake let me do it like this so if you notice both of these
are returning the same thing right they’re the same function let me just
remove these for a second yeah let’s also try something else let’s see if
they are same and they are so as I say jQuery or dollar it is the same thing
okay so now talking about what we are doing here let me just okay so I have a
simple HTML file which has a div tag now notice that there is nothing inside this
div tag so even when I’m loading this page right there is nothing to be
displayed it’s a it’s an empty HTML page with nothing inside it everything is
basically I have I’ve commented out everything there is only one div tag but
it has nothing inside it now let’s suppose I wanted to display something
after the page was just loaded how does that work so let’s break it apart piece
by piece so I have dollar it takes something called as a document so when
when I pass in document over here jQuery understands that I am referring to the
entire HTML document right from the very top and then I’m going to use something
called is ready ready is a function again it’s a function so this is a
function the one that I’ve highlighted which has another function on top of it
JavaScript allows us to do the okay that there are functions defined on
top of each other it is also called as chaining Rev function top done another
function so I am calling a function which takes in a parameter the parameter
is another function so I know that we do have a lot of functions here but just
bear with me for a second so I am basically telling the browser that hey
when the document is ready execute this function the one that I’ve just selected
just run whatever is inside of it so I’m not setting a timer here because I don’t
know when the page would be loaded or when the page would be ready right I’m
just saying that hey if I never the document is ready to whatever is inside
this function so let’s try it out let’s do a simple console dot log document is
ready let me actually also comment out all of this now let me reload the page
so this prints and let’s see if we had this outside let’s set it on the line
number on line number 36 and then on line number 42 so if you see write line
number 36 is executed line number 42 is executed but the document got ready
later on it executed this it said this instruction it moved on to this
instruction and when everything was done and when the page was ready so the page
the document was not ready until in unless it comes down to this one unless
it goes through everything the document is not considered to be ready by the
browser so this function does not get triggered
but then internally JavaScript triggers this function once everything is ready
so this is really the first snippet of code I think that most people go through
when they’re writing jQuery that when the document is ready do something and
the next thing is that you want to display something on the on the web page
now jQuery allows us to select an object or select the element in the Dom or to
break it down it allows us to select a particular HTML tag now selection can
happen through multiple ways it can happen by saying tips so it will select
all the divs available in the document all the tips even if there are like
thousand ten thousand days it will select all the tips not recommended that
you do this because naturally it causes a lot of problems so like CSS if you
wanted to set the style on all divs that is what you would do then the next
option is to select it by ID so if you look at this over here the ID is ready
demo so I can just set the hash tag like I would do in CSS so CSS would be
something like this right or let’s reduce it a little bit right so
hashtag ready demo in a similar way I can do hashtag ready them over here
which tells jQuery that or the browser in fact that this is what we are
referring to this is what we want something to be done on what do we want
some to be done on we want to set that text inside it because it’s empty and
what it takes to be document is ready so we were doing a console dot log but now
we want to show the user that hey my tab page is ready so notice here that page
is ready now let’s reload the page as you can see it appeared it wasn’t there
it is my code which put it there so anything I print over here it would show
over here and this happens after to a low document dot ready so when the
document got ready then this function was executed and the function execution
wanted this to happen first select the pack that you want to
make changes to so I want this node to be modified manipulated I want that
takes inside it to be web pages ready and that’s what I ended up doing going
back to the slides so it is executed as soon as the document is ready for Dom
manipulation and we assign a function right so moving on now another thing
that jQuery allows us to do which I was talking about is chaining or even even
actually javascript allows us to do is this chaining functions on each other
where functions are executed one after the other
now I know that you haven’t that these are not familiar to you so I’ll go
through them one by one so let’s suppose I want you to set the color of this from
after it loaded jQuery provides me with a method called as dot CSS and whenever
you’re kind of searching for these things online you have to refer to them
as dot CSS in jQuery and you will immediately open the documentation on
Google alert or jQuery website Sociedad CSS in jQuery this is a method which
takes two parameters the first parameter has to be the CSS property and the
second parameter has to be the value okay so let’s run this for a second and
see the result if it works or not okay it already did right web page is ready
we can also chain another one to this or let’s
suppose don’t destroy a different one let’s try
– like font weight and let’s set it to 700 now it becomes bold if I make it as
a hundred it is not bold they make it as 1000 it is okay it’s not pulled
yeah 1000 is not a valid property yeah 700 is so it becomes bold and I can even
change the color again so I can make it blue now oh ho I think the color if you
look at it it’s a sequence first do this set the text then color than this so
again I’m giving directions like to a frame but this time the canvas is ready
and probably it’s a second frame which is my JavaScript and jQuery frame which
I am Telling that hey now do this now do this now do this and to try the last
thing that is given on the slide deck which is fade in which basically tells
it to fade in sort of an animation you’re going to go we’re going to talk
about it more later but let’s look at okay this is not slow enough let’s look
at how to make it slower so this is a jQuery documentation I’m just going to
try and figure out how to make it slower okay so it takes a number I can give it
a number I can say I think it’s in milliseconds so I can say that hey show
it in thousand milliseconds or 100 milliseconds
okay let me set it to 5,000 which should be five seconds which is pretty slow
okay right I think my live reload is enabled and that’s why it’s kind of not
doing really it’s not truly showing that effect let me try it out like this okay yeah you right moving on okay
so jQuery also allows us to declare functions of our own on the dollar
object now this again goes back to the fact that functions are also objects and
objects can contain functions on top of them right so so an object in JavaScript
can have like one of the keys one of the value of an the keys be corresponding to
the value which is a function so to define a custom function on JavaScript
this is sort of the way we would do it where we would call dollar dot F n dot
my custom function and then define a function which would do something and
then we can do further things to it so if you have to define your own jQuery
functions there is a possibility to do that as well without you know rewriting
the entire library however whatever it suggests is that just keep it as a
mental note for now because it is preferred that you are a more advanced
user of sorts who has done this who has sort of familiarity with Java JRE and
Java Script quite a bit to be attempting this but it’s a good to know thing that
you can extend the library and one of the most beautiful things about jQuery
you can extend the library to your own means and fashion ok coming to querying
the Dom or selecting various parts of the Dom object using jQuery and
JavaScript ok so I have an example for you it is nothing but a simple list okay
and what is happening in this list is that there are three items
wait let me actually just show you the HTML right so this this is a list there
are three items in the list there is outside it’s an a tag not referring to
anything but probably we can just refer it to google the
the div tag inside it which has another a tag inside it it’s a demonstration
purpose not not necessarily that you will build something like this but it
could help me demonstrate a certain amount of concepts and then it has other
elements inside it okay now okay so as I just showed you that we queried the dorm
using the ID selector but we can also use other CSS selectors as well but
let’s take to the ID selector for now now over here the example that we have
is that if there is an ID called as fruits and we had to take that text out
of it it would return the entire li all of this inside of it if we then go to
again this is a separate way of referring to it this is another way and
this is another way neither one of these is right or wrong
use the one which you’re most comfortable with so I think a lot of you
might be comfortable with the first option this one is a more generic one
and this one would only select the li inside it okay so as I have told you
that jQuery would relies on CSS selectors it uses the same power of them
now there is the ID selector it looks for a unique ID and selects it and sets
the text inside it we’ve already done this demonstration right moving on to
the next one then there is of course the class selector as well so if I were to
let’s suppose go to the document and change the class to read e1 and change
this to read e1 as well and change this to read e1 and then go and then reload
the page it still works because now it’s a class so instead of
the hash it’s a dot now the question might be when to use which really
depends on you and really depends on your on let’s suppose if you are making
the project but I would stay I would typically say stick to one but in case
you don’t want to define extra ID so let’s suppose you have a you have a div
tag right and you defined a class on it now you don’t want to add extra HTML to
it by adding an ID tag and you know referring to as something else in
JavaScript and forgetting the reference again and again so it might be
convenient to use classes wherever they are
in case a certain a certain element of your HTML does not have classes then you
could probably define a dev on it oh sorry or you can probably define our
ID on it and use those and then there are there is naturally the element
selector so let’s suppose I will add a heading over here and I’ll say heading
h1 close it and once the page is loaded we’re gonna say dollar h1 dot CSS color
I’m gonna say red and we’re going to then go ahead and rewrote that page
right so if you solve for every second it is black but then it quickly
transitions to red so even by using the h1 tag that is
pretty much like how it would work in in your in your CSS you can set it up or
you can change the text entirely and we can do this we come to this and
we change I shouldn’t ask you change Irishman text okay moving on then of
course there are the attribute selectors which is by saying that let’s suppose
there is an a tag and it has the target set as self or it has a H ref which is
said to google.com and I want to select it and I want to modify the color of it
so the way this would work is that let me just add a tag over here and the target is so it is an attribute
set on it and then there is another one okay so what jQuery allows me to do is go
over here say select an e-tag which has target equal to self and you change the
CSS color from blue that it would typically be to green okay I forgot the
quotes quotes need to come here and I’ll change this to double quotes okay let’s
try it out so if you notice the color has changed
let me mute all of these out so that you can see clearly the color has changed if
I were to change it from self to plank the other one the Google blank one gets
colored let’s see if I change this to yahoo.com okay let’s suppose you made a
mistake both of them say both on say Google inside it like to the user but
actually one is for Yahoo so what you want to do now is you want to select the
one which says yahoo.com and we want to change the text to say Yahoo right
so if you notice earlier in the HTML this is being set as Google cells but
then we changed it we selected on the basis of the attribute and then we
change the text inside it okay so this is how you will basically select based
on the attribute so attribute refers to so I know ID in class are also attribute
so it might be a little confusing in terms of because I think many of red is
the opinion of judge CSS it would refer to class an idea the attributes as well
and it is they are attributes rightly so but then what we are referring to here
is kind of attributes which are not ID or class which are not ID or class okay
next is universal selectors which is basically a star stem star symbols which
will select everything in your document not recommended that you do this it will
eat up a lot of memory probably crash a website on the user’s browser so yeah
but the star symbol will essentially select everything okay
next is position selectors and pseudo-class selectors right so let’s
try this out actually on the on this particular one now if I had to select
the Li let’s suppose I to select the item list item on my list and then I had
to select the a lie and I have to do the CSS color as
red let’s see what the result is okay this did not work wait maybe this
will work okay so what happened is that this is the way that you can select the
children inside a parent so what yeah what I said is that he select the item
list the element with the item list and then go to the first one inside it go to
the first one inside it and set all li as with the CSS as red of color now what
if I had to do this only on the first one so if I had to do it only in the
first one this is how I would do it notice how the difference is only the
first one is colored red so I’ll just remove this because it might be
confusing some of you yeah it’s just it’s a CSS precedence which is playing
here so let’s suppose first one is coffee so first when he set his coffee
if I have to select the second one I would go a second okay I have made a
mistake let’s look at yeah let’s try bit too yes I think this just works only with
first and not with second but if you have to just select the first one I
think it also works with the last yeah it works is the last one as well but
okay right so it works with first and last but not with second third or fourth
so it’s more about personal asset easier but I think then if you think about
logically the number of items in a list can be hundred as well so it would not
be possible to kind of name the middle ones the second third because different
people will refer to them in different ways and that would be unmaintainable so
you can see the first or the last of a thing as well using first or last now
and then of course the pseudo-classes so the other option here was that if I
suppose knew that everything else had to be turned away I could do it like this
so I said the not and then yeah so here is what I did
I said a which is not which does not have href as google comm said that takes
to Yahoo which does not so not is also available as an option so next is
traversing the dorm so traversing is basically walking through the dorm it’s
like walking the path walking element by element by element by element and with
query selectors which is the first part you can make the first selection but
then if you want to keep going down a particular nested set of tags in your
HTML that is where traversing the dorm will help you out and then there are
some common functions available to us fine finds all matching elements child
children if same is fine but moves only one level down closest moves up the Dom
tree so it doesn’t move down it doesn’t move inside moves up the Dom tree until
it finds the matching parent parent moves up the Dom tree but up to a single
level so closest will find the closest match even if it’s way up parent will
just move to the next immediate single level okay it will find the parent of
this particular node next moves down and targets the immediate falling sibling
now what is important to notice here is the sibling part it will notice it will
go to the sibling it will not go to a child so if there is a li tag right so
Li tag if you call it on an li tag it will move to the next Li tag it will not
go to anything inside it any HTML inside it previous is just moved just like next
but moves up so it moves to the preceding sibling and siblings it
targets moving up and down so if I select it on an li tag it will select
all the other siblings first gets the first element from the selected side and
last gets the last so I think that kind of shows where I mentor on Collier so
first and last basically first goes on the first one and the last only on the
last one not on the middle ones but if you had to traverse the middle ones then
probably something next or previous applauses that’s
something that will come to help so let’s see a couple of examples of each
one of them okay so let’s mute this out and mute
this out as well okay
so what I’ve done is that I’ve added a simple button here and I’ve added a
click function on it now what what I’ve done here is that it whenever I click on
this button this is present on the web page here
something will happen now what that something will be is being defined by me
here so what this is going to do is going to go to item list this you will
that you have created is going to find the a tag and to make all CSS it’s going
to make them of red color so let’s try this out right let me click on the
button so all the a tags went red coffee was not an e-tag in fact let me so that we can remember and we can say
this is yahoo.com and he can say this is and if I click on click me see how it
found only the a tags and not coffee and not milk and not tea and it said them to
read so essentially item list find a center
fellow to rate next one is the children example so if I was to do this let me
try and do this or let me first show you this example so we did find right we did
an item list but let’s do it on the first li instead which will select this
particular Li tag let’s see what the result is pretty much like the same one I selected
the the Li the list item first instead this time and I set the color to red
now what if I change it to be children what will happen only google.com only
google.com gets colored red why is this because children goes to the next
immediate one which is this one it will not go inside
it will not go more than one level deep if this was outside the div tag here
this div tag contains this right this was outside it would have worked but
then it is not so this doesn’t work out so children goes to the next immediate
one let’s go to the closest one let’s see what the outcome is try to guess
before I demonstrate so closest goes to the immediate closest
one let’s look at the definition once moves up the Dom tree until it finds the
matching element in Dom so it moves up the Dom tree actually okay so nothing is
happening the reason is that it is moving up it is not moving down it is
not moving down so we need to find something up here so if we added a tag
over here which is outside of ul so it’s no longer about being inside ul outside
ul a tag okay wait you yeah so I think it would be better if he
so inside were what closest does is that it tries to look for the closest parent
of a particular type so what I’ve done instead is that I’ve selected this
particular key tag which is inside alive and I’ve said hey
find the closest ally and set the color to red this is what this is going to do
it’s going to go to the closest ally and it’s going to set the color to red the
page is reloaded let’s click on this button and if you noticed the Allied
this time the Li gets turned color to red so there has to be a relationship
what I was trying out earlier was that there was no relationship between the
the Li tag and the a tag outside it but now we know that it has to be a
parent-child relationship there it tries to find the closest parent up the chain
now going to the parent example fear again I’m going to select the inside a
div a tag and we’re going to find the parent and we need to give it a border
of one pixel so just right out okay so the div tag containing yahoo.com gets a
border of one pixel over here okay next is o Nexus next so you’re going to go to
the first Ally we’re going to go to next and we are going to give it a CSS border
of one pixel first Ally and it gives it to milk because it are going to move to
a sibling not a child not a parent but to a sibling so at the same hierarchical
level as it self let’s go to the previous one okay so in fact let me make
it a little simpler so it will go to the last li and then it
will go to the previous sibling so it will go to T and part from T it will go
to milk so this till this it is at t then it goes to milk and then it sets so
CSS next siblings so first you lie then the siblings and sets them to the border
okay we could also do it like this where we select this and right instead of love you can do first
and then it will set to both of these or last will do it to put table of months
okay next is first so let’s see what this does for us we’ll select Li and
we’ll select the first one so we select Li and we select the very first and I
that we find and this one will select then the last one of course there is
another way to do it so there are multiple ways to do the same thing my
recommendation would be to select the one that you’re most comfortable with
that you remember the top of your mind and just use it this really thick little
right or wrong here 4:54 big nose and eventually you will get into the mood of
using these variables or using sorry using these functions in a way which
makes sense which which is sort of convenient for you at the given moment
so they come in handy when you are dealing with a lot of complicated Dom
manipulations for beginning purposes keep your focus on the first part that
is just selecting an element using the class identifier or the idea identifier
or the tag identifier so one of the most important aspects of jQuery is Dom
manipulation doing Dom manipulation can be cumbersome based on different
browsers each browser will react in a different way to your instructions if
you’re writing plain JavaScript however jQuery comes to the rescue with
a bunch of methods which are around Dom and which handle that difference from
browser to browser for us now as in anything related to programming or
computer science there are four things that you can do to any particular object
and those are creating it reading it updating it and deleting it so adding or
removing is creating or deleting modifying is updating copying or cloning
is is reading and then writing so these are essentially the four fundamentals on
which a lot of things are built on so by manipulation we simply mean that any
changes whether it’s updation creation or deletion or simply even reading it
those are any sort Dom manipulations that are available to
us now there are certain simple methods to manipulate the content inside a Dom
element so one is the Dom element in itself manipulating the Dom element in
itself and then even the content inside it so in last class for example we saw
that there was an empty div tag but we placed some text inside it after the
page has loaded right there is an example of content manipulation so
sometimes you see it on website right when you click on a button something
reviews itself some answer let’s suppose a question shows up if you have taken
one of the quizzes here or something else happens so that’s an interaction
where you are clicking on something and the response is that the text appears or
the content manipulates there are primarily three values there are three
ways one is the text method to update the text inside our HTML there is a HTML
method to insert or update the HTML code inside an element so and then there is a
value method the Val which can get values from an input box
or set values inside an input box now the difference between text and HTML is
natural that text is simple text plain text but with HTML you can actually
place HTML inside your document so let’s quickly jump into an example so what
I’ve done here is that I’ve written some simple HTML it’s inside a container tag
right there is a question there is a answer box
the result is empty right because the user hasn’t answered a question till now
and then there is an answer over here so we will show the result of what the user
submitted as it is a correct answer so I’d overhear what I have done is that
once the document is ready I have said something called as a trick listener so
the be covered this in the last classes where that this is sort of an event
listener so this is going to come in depth later but for now what you can
understand is that whenever the button is clicked I want it to do certain
things so the first thing that we will do is that it will get the value from
the answer box and let me just open it appear so that we can compare side by
side so this line over here answer box it
refers to this one right i D we selected it dot Val it gives us the
answer then we check if the answer is dead e because we know the question is
India right of course this is just for example sake in real world like the way
once you’re building it then probably you’re going to add some other
operations to it and if the answer is correct in the result one we want to
display that your answer is correct if the answer is not correct we want to
display some HTML instead with the span style of with color red saying that your
answer is incorrect and we want to display the correct answer as well using
text so we have ended up using file text and HTML all three in the in this
example so let’s quickly run it in the browser and see how it works
so let me give the answer this Calcutta and submitted
okay seems like I made a syntax error just quickly fix it it says it is over
here okay yeah this should fix it let’s
typing Calcutta so as we’d wanted it to do in case of a
incorrect answer your answer is incorrect right is displayed over here
and the answer tag the answer is displayed let’s look at the HTML if it
produced right so this did not have content inside it before we started but
now it does now it does have content inside it and let’s try for the correct
one if I answer as Tilly your answer is correct that reload and I type in Delhi
it will say your answer is correct it is added to this you can in fact see the
Dom manipulation happening in front of your eyes it by leg so if you’d notice
here the result is empty let me type it in and just keep observing this part
did you see it we see the change this is not present let me do it again
this is empty right now there’s nothing inside it I type in daily I submit and
then suddenly there is a small animation that you can see it blinked for a second
that is done by the chrome dev tools that is not essentially related to
JavaScript as much but it’s just an effect that you can see sort of see that
the Dom was manipulated you can see it taking effect in front of your eyes let
means are to either incorrect one as well keep observing the section here
since we saw both of them got affected now let’s see it again
you see both of them got affected result as well as answer so yeah I mean it just
talks about the same thing that we can set the text HTML or value now the other
thing is that we can also add or remove Dom elements which is also very very
powerful that you can act your HTML after the HTML has been served so till
now what we were doing was that we made a HTML document and it was fixed right
like you could not add more P tags to it more dev tax to it but let’s think about
something like the Facebook feed for a second it’s an infinite feed or any of
the social network feed as you keep on scrolling down it just never ends it’s
infinite so what is happening over there essentially Facebook is adding more and
more div tag or stories as they call it or posts but that is essentially HTML
code and it keeps on adding adding adding and adding it’s an infinite list
it keeps creating so it does start through JavaScript with JavaScript
creates the Dom and it just keeps on adding to the feed infinitely and then
there are a couple of methods available for doing this so after before append
prepend and remove all of them work in different ways so let’s dive into some
code and see each of them in action so I’m going to just comment this out
because we don’t need it anymore okay I think I might be happy so let’s remove this as and okay let me take this place it over
here okay so what I’ve done is that I have
created four boxes on my web page I’ll just show them to you in a second
so here are four boxes after before append and prepend I’m going to show
examples of each of the function using each of these boxes so they are present
over here and the styling has been done somewhere over yeah yeah so there is a
color box it has a weight that has a height it has a border margin and then
there is an after tire on it which gives it the color so the color is given to it
by us now each of the boxes has a click event on it so once it click on it it
will append something to itself which is going to be again a div tag this is
going to be another book so clicking on one of the boxes will add another box to
it for the purpose of demonstration let me even remove the other boxes so that
we can only concentrate on one box at a time so I’ll even comment this out only
one box and the box that I’m going to attach it is going to have the class as
attached and the color is going to be yellow okay so if you saw this
particular thing got attached to it click click again another one happens
now why they are appearing vertically like this that’s more of a matter of CSS
but if we look at the Dom this concentrate on the Dom we had this a div
tag right so what after does is that it attaches it within that particular div
tag so after we’ll boxes will come after
this text so it is not outside of the div tag that’s a different one it is
inside the div tag in itself that we selected so dot after dot append
and it will keep on adding keep on adding keep on adding keep on adding
okay let me show it to you again observe the DOM
so let’s look at it the dev tag the HTML that I wanted to add was added after
this in fact I can show you another example
so let’s actually do it like this okay yeah with ul again it will add to
itself right right right right so it is not outside it is inside very
very important to remember that okay let’s remove this and then let go to
before what happens with before so in before again we just going to call this
method taught before as you just saw on the slide and let’s see what happens
okay so now it gets appended before this gets upended before before before let’s
see what is happening over here now before is outside the box it is no
longer inside it’s not attaching to this text so this can be very confusing for a
beginner it adds an element after the specified element right but after does
it on within the tag that you have selected before does it outside the tag
let’s go to the next one upend so upend will again upend it
so after and a painter pretty much similar here that they’re appending
within the color box they’re pending within the original dev tag definition it adds an element as last
child to the specified element so it keeps adding as children one after
the other but prepend and let’s unmute this for prepend phil attached before the
element settle add parents to this particular element I hope it is clear so
please notice whether it is inside that particular tag that you are appending to
that you are calling append on or it is outside that’s the primary difference
between after before a pendant prepend so another very very useful jQuery
method that is available to us to manipulate properties and attributes on
our HTML Dom is the attribute attr method it allows us to either get the
values or set the values on our a tags or image tags or anything that for that
matter any any kind of time but one sort of usefulness would be sort of let’s
suppose you have a list of links and you want to based on some condition replace
them with something else or you want to change it to something else
so let’s start with an example suppose even if tag
guru okay and the target here is blank is yahoo.com Yahoo and they suppose there is a button here
IIT is something it is let’s call it link fix so we can
all this code or let’s just keep it over there and we can just simply write fish
oh yeah and it would be something like struggling fix dot click function and these are
hey find all the attributes and all the a tags and set the target to
flank so let’s see what happens so
calm the target is not blank it is cells which click on this yahoo.com changes
right there in front of your eyes the target attribute changes if this was
self and even this was selves they’re doing this to change both of
them another thing that you can do is we can just get the values first
but target let’s just first console dot log these values and see what we get
Oh to console right we got the first match in fact let
make it as blank let’s see what happens if you have two different sorts of
values you click on fix my links and again we get itself so I think it would
pick on the first one there so in case you have multiple matches it would pick
on the first one so let say the condition saying that if target value
protocol please take the a tag and set the attribute – clack so you can see that it said the
attribute to blank now interestingly it set it to the last one it did not set it
for Google so only for the last one will it ok wait right so sorry so it will set for both
of them and if this was blank so then this does not work because if
there are multiple matches so it will stop at the first one it will stop at
the first one and because it will not find it to be blank or we can do something else we can say
because we have learnt the HTML tag we can say a dollar a dot HTML we can see
or we can do this we can do a control dot log out of this and see which one it
did actually select we have clicked on this to this
okay so this one essentially gives us for both of them let’s try this instead
let’s see what this results in right so it returns just the first one
so because this condition is not setting true even though there is a document of
itself so it’s very important to remember this we’ve been dealing with
the attr that if you’re searching for something using it it will only go to
the first one but if you are setting something using it it will set all of
the elements which match so if I just did it outside then even this one would
be fixed otherwise it will go individually to each and every a when
you’re getting the value now there are various methods which are
available on top of this one of them is remove attribute so it removes an
attribute from the selected element it then there is has class which checks if
a certain element has a certain class or not there is add class there is a remove
class there is toggle clasp so toggle clasp is basically it will check if the
class is present if it is not it will add if it is present it will remove then
there is the prop as well which is kind of introduced in jQuery 1.6 and
attribute the attr method is internally called prop and it gets the value of a
property for the first element in a set of mashed elements so this is what we
were observing that it was getting the first element in a set of mashed
elements or set one or more properties for every measure element so this is
where the behavior is coming from because attr is internally calling brop
prop so and and it says very explicitly over here it gets the value of a
property for the first element will be the first element in the set of mashed
elements or sets for normal properties for every master element that is
significantly different now let’s quickly run a couple of examples for
this one let’s see what remove attribute and each one of these method does for a
quick demonstration purpose okay for removing attribute okay let’s suppose it had an ID and for some reason we wanted to remove
the ID attribute so we can do it in this way you can say remove attr and
we can give it ID and let’s see if it removes it or not so it is currently
saying ID we can fix my rings the idea limit is removed if we told it to remove
HF it’s riffs are removed see now the links
do not have any edge stress we can tell it to remove target as well and they
will be removed too next is has class so you need to pass it
the name of a class so let’s suppose we call it color box
they call it Oscar and they say has class after equal to equal to true
then we want to do something which is available as our class so then let’s add
a class or rather let’s remove class I’ll do remove class after class cold in thing
class called as Gordon link simple demonstration we’re going to call
it I’m going to give it the color of gold by removing the already present one
so we’re going to check if it has the class after if it sets out to be true
then we are going to remove the class after and we are going to add the class
cold link let’s try it out so as you can see there is a slight difference already
in the way Google is being represented over here the CSS has changed now let’s
click on fix my links if you observe that goes away and the Colden link class
has been applied I made a mistake in the style one yeah I made a spelling mistake
let’s try it out now now observe that it has been given to both of them not just
one because I’m using a general one right I’m adding class and everything so
it might be a good idea to not do this but instead say
they select to it like this and then go for class after torch remove glass
faster dot add glass golden link so this way we are trying to add it only
to the Google a tag and not the Yahoo a tag so you see only add it to the gold
any type because we selected a particular one so we said dollar dot
after remove the class and then add another class to it and that gets
modified okay the next one we can do is dollar a toggle class after so now we
are saying that the elements which have after class remove it the ones that do
not add it so you see how it’s switched from one to
the other we can also add another one and not another one call it golden link
put them to come golden and we can add another one saying total plus
color box so this is based on chaining I’m chaining multiple effects together
so now it’s it’s a complete switch from Google to Yahoo let me ask you to man so if you notice the dorm is changing
accordingly every time I can do this a number of times this will keep happening let’s go back to the slides right so as
you can see in the example that I’ve just shown this follows a slightly
different example perhaps you can try it out at your end and see the results or
you can try out the example that I gave you now another one is to clone and
again very useful you can sort of clone an element and you can insert it after
or before or basically do something with it you want to clone let’s suppose one
particular link or you want to clone an HTML tag so this is what helps you out
with so let’s change this to clone my links
and let’s remove this let’s remove this as well and what we
will do is we will say a dot blown okay maybe insert after
so we can be just inserted after that a tag itself so let’s see how this works so why did that happen because it
selected all the attacks not just the first one
so it’s selecting all the e-tag including all of them so instead I could
let suppose creator IDE saying original or master and we can say hashtag master
or clone and so it after I suppose ideas Downes and I could do this it said after heist
are clones now it gets inserted after hashtag loans let’s see if it append or after works on
this okay after doesn’t
to work let’s see if append works on it oh right so so it after that wouldn’t
work keeps on adding and then there is
another one let’s suppose you have some sort of event set on it and any sort of
data said on it then you need to set clone you need to
pass it a boolean of truth by default it’s false to copy the events as well so
in case it’s a button that you’re copying or it’s one of those boxes this
is that we just made and you’re trying to copy that box and you want even the
subsequent boxes to respond to it then you would need to set clone as true that
even those boxes would have the event so let’s try it out with this I just
noticed that this needs to be after not append and I think now it should append
after the Box not inside it so we will try to see that we clone this
and we were to insert after this one we are going to insert after let’s do it
after our color box let’s insert it after the color box now
if I click on this box nothing happens they click on this
another set of boxes come up let me reload let me zoom out okay one box
multiple boxes but if I click on any other duplicate boxes nothing happens
click on this box this box nothing happens so then I need to say this is
true now what will happen is two boxes if I click on this either one of them it
will replicate it will replicate even this works it replicates does this to
add the event handler one again sorry wait this is after now these are coming after it right
these are coming outside moving on to the next one so there are
two approaches to move an element around the dorm one is placing the match
element relative to another element and the other one is placing an element
relative to the master elements so one basically what it does is that it takes
the match element and places it relative to another element or you take an
element to replace an element which is relative to the master element and that
is where append and append to come into the picture there is a slight difference
between the two now jQuery provides us with something very
useful which is called as a dollar dot each it’s a replacement for the
traditional for N or for loop in Java Script and helps us out quite a bit
actually so let’s do a quick demonstration of this over here and the
way this would work is that I would define an array of let’s suppose num
list is equal to 1 comma 2 comma 3 comma 4 comma 5 6 and then I’m going to say
dollar at each I’m going to pass it the numbness
function and it’s going to be the index in the value and we can simply says to a
console dot log index and value let’s see what the result is let’s look at the
console 0 is 1 1 is 2 2 is 3 3 is 4 4 & 5 5 & 6 so it allows you to eye trait
without using those initializations of I is equal to zero increment decrement
operator you can just loop over you think of all each it gives you the index
and the value that you are looping over can be pretty useful especially if you
are doing any sort of functional programming and naturally it will also
allow you to loop over a set of link elements any sort of list elements so
that would be something very typically useful in the context of Dom or document
object manipulation if you wanted I suppose loop over an entire list of
allies then this is going to be super useful so let’s try this out quickly so
I have a list over here let me take it out place it over here let me mute this
let me mute this as well now what I’m going to do is that I’m going to select
all the Allies and I’m going to call dot each of them and I’m going to so it’s
going to give me an index and an element to check is element dot
our first just do this let’s just see what is inside each of our elements and
then take further action okay let’s see
we are getting first and then take further action right so we are getting Li tags each one
of them let’s see if
any of the jQuery functions on there so you need to keep trying out things okay
and I mean that’s very very sort of important there will be failures there
will be chances that certain things are not working but don’t be discouraged by
that I mean if you think what it is quickly right you try a couple of times
one thing doesn’t work but something else does and that gives you a better
understanding of what you’re dealing with so let’s look at what type of thing
it is that you’re getting over here so it’s an object so and of type la
and now we can do various things to it so another way to deal with this is with
this variable in JavaScript let’s try it out let’s see what we get over here
now we get Google Yahoo and Amazon we can also check for pass class
golden Ling doesn’t so let do it for each of the
elements let’s do a toggle clasp so each of the elements care at agra
floss let’s look at what happened this is the UL we are dealing with each of
the li get a golden link Tony floss of course the a tag and itself has a blue
color so that overrides it in case somebody’s confused that this is still
looking as blue and not yellow it’s just that this overrides the outside one so
we I traded over each of the loops and essentially we ended up talking the
classes to a wooden leg another one is EQ which selects from the set of matched
elements at a specific time so let’s suppose we only wanted to add we only
wanted to add it to the second one and not the first one so the way we would do
this is that forget this for a second this is just basically looping over the
entire thing instead what you could do is that you could add some code like
this and we could say equals to dot dot plus wooden link so to get selected to being it it being
zero index naturally now one and this one will select zero if we set it at an
index which is not available it just does nothing so it allows us to select a
particular one from a list of elements that we might match so it is actually
acting as a filter right it is filtering out the other elements that we do not
want to touch or do we do not want to manipulate now there is another function
available which is called filter in itself and you can pass it a selector so
dot EQ basically takes the specified index so you need to consider the fact
that this is sort of like an array this is sort of like an array that is
returned over here and we are saying that we want just the second element of
the array or the falls to the for a particular one but let’s suppose a
matching criteria is a little different in this something around the fact that I
want to select an ally which has the class
were to filter out all the alloys which have a class of middle so let’s suppose and let’s suppose we actually add some
styling for the middle one let’s suppose we are at color as light blue
and once we get to it we want to do a toggle clasp of the golden link okay
let’s put on this quickly okay seems like we ran into some trouble right I
miss the dot oh yeah because I want to write so you see the middle to get
selected so EQ just allows us to select one but if you want you to select
multiple within a set so if you had forward and you need to select two then
you will go forth on the lake filter where all the elements which specify a
certain criteria with EQ your fixed to one element because it can only take one
index at a time naturally and you need to know which index as well over here
you are sort of with filter you are setting a condition that hey give me all
the elements which have the middle class set on them which might be multiple
elements as in this case then there is something called as has
which checks for certain things and accordingly sets the CSS or you can you
know do further operations on it so in this case it will check for descendants
and if it finds a matched element based on the defendant then it will do certain
thing so let’s suppose over here the example is that if my li in turn has
another set of Yule tiles then I probably want to set a CSS on it okay I
want to probably set a CSS on it so let’s actually try out this example in
itself I’ll remove this and let’s suppose the last one is not this
straight it is something like another you will inside it and says it says something they so a lot of times websites have to
web addresses based on the country that they’re serving so Amazon France Amazon
dot and and let’s suppose there is another one called Amazon dot us now we
what you want to do is that we want to check
it has a ul okay this Li has a ul then I want to set an attribute of background
color as light gray I suppose or let’s just make it style outside a
style you can set the background color as like gray let’s run this
okay seems like we ranked some trouble let me try it with CSS so we set it up but right this one works
so maybe the background color the property doesn’t work on ul tags so this
works and we have set the background borders as this and now yeah let’s try
who here is background color I made a spelling mistake somewhere let
me try it out again let’s try the same color blue yeah so
this works now please notice that it’s not applying on the UL but it is
applying at the Li level it is not applying on the child it is applying on
the parent in itself but you’re filtering it out we’re filtering it out
on the basis of which particular element do we want to attack now what not does
is that it removes from the set of master elements so quite simple let’s
suppose I want to do this for everything which is not in the middle so not is
take the opposite of has that’s it and I think over here the first thing the
third one are selected the others are you know fair enough so jQuery also has
support for data API which has been introduced in html5 which lets you set
data attributes or get data attributes from the HTML that you might have set up
so let’s have a look at an example I’ll just explain it to you in a bit so let me comment this out now
I have two buttons here one will attach data to a development and the other one
will remove it and these click events are set on the same instead of test
object we can do it something like this data they support it as God 200 and we want
to get the data of God this out let’s see what we get so we have the
development over here no way you’re talking about this particular
development let’s add something to it let’s add an ID tag gate our example and
let’s use it like that because then it will not confuse with the other one you so we need to set the data on this
particular div tag right we will simply pass it an object like this and then on
clicking the button too we will get the data associated with it so let’s do this
let’s remove these zeros assuming this has worked once you click on this it
should display a value of 200 in the console and so it does so this is how
you can use data attribute and you can use it on to set any number of things
over here in fact so they suppose I said items
then I do this and then I can also do it for items and as I reload again attach
it to them move this and then shows both of them so 200 for cart and 300 for
items coming back so jQuery also provides us with a bunch of effects such
as show/hide and they are used for showing or hiding the Dom element so of
course you can remove elements you can add elements you can also show and hide
them this is something which is very very commonly used and it takes two
parameters these are essentially functions and they take two parameters
one is of speed in terms of how slowly or fast or immediately yours you want to
display or not display them then it takes a function as well so in case
they’re suppose after showing or hiding you want it to do something else
based on the element being shown or hidden so the callback function is
provided where you can execute any code that needs to be executed after the
element is shown or hidden so let’s do an example for this what I will do is
that I’ll set up my HTML on the boxes that we had so let’s do it on the boxes
and I’ll show all the boxes yeah let me give it a glass of container
and they give it a display off
line-lock and let me give the container didn’t leave it empty for now we’ll see
if you need to fill it up let’s see how our page looks right now so our page
looks like this let’s remove the button tags that you were using for the data
example so now we just have this and let’s add a button the ID of show boxes the button which says hide the boxes let’s give some space within them let’s
see how led but of give up I’m brave boy here as well okay so now you have two
buttons over here let’s come to our script let’s take this and move it
somewhere you comment it out let’s comment this out it will come back
here let’s try to stretch JavaScript for these boxes again click events
show boxes dot click function is ready okay now what we want to do is before that let’s defined for hide boxes
as well say is that anything with the color box
class hide it and oh you’re similarly will say
anything with the color box class show it oh we go
seems like it is not working try to figure out why is that happening I have
missed the ID tag so very very important sort of a silly mistake in case your
code is not working immediately look at whether you have missed the tags or not
let’s try it out again the boxes are hidden boxes oh sure the
box is hidden the boxes are sure now this is a sudden knee-jerk sort of
reaction where it is just immediately coming in and going out instead it would
be better if we could add some sort of slowness to this motion where it would
gradually happen so let’s add 500 milliseconds to each one of them we hide
our boxes now look at the difference suddenly it becomes it seems more
user-friendly right it goes in and out slowly and let’s make it 2,000 and then the certain pace because eases
into that motion it’s very soothing it’s very nice the user doesn’t get done each
oaktree action as before that it was just like appearing and disappearing
next is of course now the other thing is that we can sort of combine these two
buttons together and say that toggle boxes or play suppose let’s not do that
lets it comment it out create another button which says let’s call it toggle
boxes let’s add another event so now what we’re trying to do is that instead
of defining two boxes two different buttons we are going to do a toggle
toggle essentially in and jQuery is basically either one of
the two so they’re hidden it will show them if they are shown there would it
would hide that so let’s do a toggle let’s take it for a spin right so single button
let’s look at what is happening at the Tom level
they are not being deleted from the dog they are still present the display is
not once again so just that a display:none
property is being added to them that’s all there is and we are doing this
through JavaScript back on the toggle function then there are other functions
that have fade in fade out fade to slide down slide up slide toggle which sort of
have a different sort of animation effect each one of them so let’s quickly
try out these ones as well let’s see what is the impact so I mute this out
instead however so now instead of showing and hiding we are going to do a
fade out and we are going to do a fade in on the of the color boxes
so now the intention is to make the boxes fade in or out
see there is a fading effect this is different from what you were
doing earlier if you noticed the motion of hiding them it was very different if
I do that again see it goes towards the left top it
fades out but it starts from this area and it goes towards this that is very
different from this one now these are subtle differences of
course but that’s what front end is is quite a bit about notice the small
differences and it can make a huge impact on the user interface and the
user experience with your website then there is feed too as well and faith too
instead of fading in and out where it changes the opacity on the object
gradually it will change it to a particular opacity so what we mean by
that is that it will still be present but the opacity would be reduced so
let’s try this out they’re present but the opacity is 0.5
now so it would be 1 in normal circumstances I can do the same for show
boxes now as well or let’s try what happens when I do this so this doesn’t
exactly do anything because they are already in present over there instead if
I want to do the opposite I would have to do this
so let me skate them out and now let me skate them in fade-out we’re there so if
you notice this is more for disabled kind of state that you might see on
websites for buttons or for area other sections whether they’re enabled or
whether they’re disabled okay then there is also something called a slide down
slide up and slide toggle so let me mute these out so let’s do a slide down
well let’s do a slide up and let’s do a slide up in 502nd and
similarly over here leads to a slide down
so you saw how this slide it up it’s again it’s a different kind of animation
effect and now just slid out slide up slide out just like a drawer slide up
slide out and slide toggle basically does either one of them in depending on
the current state pretty much like how we were using toggle over there in a
similar way not too much of a difference finally jQuery also has a dot animate
function now see hide show fade in/fade out slide up slide down these are sort
of animations that are provided to you right out of the box but let’s suppose
you want you to do something drastically different you wanted a sort of animation
effect where you wanted the box size of the box to grow from a certain size to a
certain size in a certain amount of time so you wanted this so currently the
animation boxes each of these boxes are 250 pixels but he wanted them to grow –
sighs – let’s suppose 270 pixels in 20 milliseconds to create kind of create an
effect so dot animate is going to help you out with that the way it works is
that it takes the property that you want to change the first is the properties
that you want to change and then the time then a callback function like we’ve
seen before not necessary that you implement the callback function it is
there it’s just in case there’s some action to be taken so let’s try and add
some animations let’s see how this works let’s call it animate boxes animate and
button and then let’s add the added animate foxes taught animate and
it’s to ten thousand milliseconds and okay we need to touch a click event this
can’t be it that’s just a button right so we need to
call it in color box but animate let’s do a simple one first they suppose
you wanted to increase the pixel width and that’s it and we want it to happen
very very slowly we want to happen 2,000 milliseconds let’s see how this works
out for us stick for a spin looks like I made an error in my syntax
on this particular line okay I did not declare it as a function
my bad I’m sorry let’s try this out nope edit again yeah I think I need to keep this between
the coats so you notice how the hottest very
slowly it happened very slowly this try this again and stay at this time that’s
2 to 300 pixel same time and let’s suppose we wanted it to move
from the top by about 40 pixels at the same time so and we want the position to
be set as absolute that doesn’t seem to be working out
let’s drive it margin-top instead maybe that would work
if it’s causing a serious conflict and yeah okay think I need to kinda sit like that so now move star
now it moves down and I suppose at the same time I wanted to on the opacity to
change to 0.8 as it is doing this action or I suppose make it a little more
dramatic so the properties are being said from
here like what do you want the CSS to be applied so you really try to understand
what animation is in a way over here animation is nothing but changing the
positioning all the styling of a particular HTML tag in a certain amount
of time that’s it so that’s what it does so this is the target this is the final
result these are final CSS property that you will end up setting on it and you want it to be done in a certain
amount of time which also determines the speed of the animation now instead of
display:inline-block I’ve changed your display:block doesn’t change much though
or let’s try with inline let’s see if that causes a significant difference to
the way they are aligned okay not really so that is what animation really comes
down to if you want you to happen really quickly you change the time and then it
will just happen so depends on what you want to achieve we want to achieve it
for that’s what dot animate does and you can of course change multiple animations
on top of each other so this is one animate and there is they can be another
than they could be another or you can combine them together it’s the same
thing I mean it depends on really what you’re trying to achieve with it so for
validation got a bit easier with html5 in case you haven’t checked out these
features I strongly suggest that you go out and check out the form validations
available with html5 in some cases however the html5 validation fails so
what you can do essentially is that you can set the attributes on the HTML tags
to do the validations but sometimes the validation fails or maybe you need very
custom or there’s a scenario where you can’t use them and that’s where jQuery
for JavaScript steps and that it allows you to do the validations using your own
custom rules and regulations and needs so talk about the jQuery validation
first and foremost you need to get the value from the form or you need to set
the value in a form and there are various ways to do it based on the kind
of field that you’re dealing with so what I have here is that I have set up a
demo which contains various fields and you were trying to getting and setting
of the variable values using each of these fields and see how it goes
so if I do inspect and I talk about the name column right to get jQuery let me
just clear this up to get the input variable name I can simply do this
and shows no value right of course because I have not put anything in here
so let me type in a deer a cup and then see Wow so we’ve already Rekha
they said the value as Eureka Inc so did you notice that the
value in the name box changed let’s try again so did you notice so just by using this
I can set or I can get the values inside a field so let’s suppose I change this
to mango just a random word and I do takes dot well see I can get the value
in JavaScript next is the password field so as you
might know that hTML is a special field for password so that the password stays
hidden so let’s see how we can get or set the values of the password field so
field over here let’s look at HTML the HTML sets the type is password
let’s suppose I’m going to set a password as 1 2 3 4 5 6 not a very safe
password but fine for demonstration purpose and if I had to get the value
this is how I could get it I hope that’s clear enough it’s pretty much like the
text field just that you need to select it using input password unless or until
you’re using some others form of selector which might be ID or class but
if you’re selecting by the by the type of input it is then there is little
difference between textbox and password getting and setting of values same is
the case of text to area so you just need to get the value using input cool
in text area and you could set it just by passing the value next let’s cover
the radio buttons these are quite interesting so I have two radio buttons
here so to see if it is checked or not I to use
the is keyword right it’s not checked to let me check
the first now it becomes true I can also do this I can set the attribute
so it’s checked right now please note is the radio button this one over here I’m
going to set it to false so does not work now there’s a reason here the
reason is that I did not select which one to set there are two radio buttons
here so let me try and set the first one you so a minor difference instead of a TDR
what you need to use here is let me just clear it out first instead what you need
to use is the dot property and you can use that to set it to false or you can
use that to set it to true and what in it is basically because input radio
matches multiple elements right because these are two radio buttons you can use
a net zero one like an array so you’re accessing the zero or the first element
of this array so now I hit the first one or the second radio button it’s true as
well now set it as false and I can do the
same one to the zero at one moving to the next one checkboxes so for
checkboxes again we can get the value of the checkbox using the input checkbox
property additionally if you want to select a particular checkbox we can pass
in the name is equal to checkbox name as well and select the same so let’s try
this up so I have a couple of checkboxes here let’s look at the HTML first so
each of them have different values and different names so let’s try it out so
input checkbox the value is one right as yourself in
the HTML let’s set it or unset it so you saw that the first checkbox was
set and we one said it similarly I can keep changing the names
and I can keep doing this for each of the checkboxes let’s see if a networks
for this or not so I do in it and I do one and let’s suppose all let’s put it
to 0 so and it works for this one as well
and now hourly suppose I were to set the first one as false I want a second see the second one is
false and this is just something that this returns usually you wouldn’t see it
when you’re typing your jQuery code because I mean your art unless you’re
storing the value but it’s just that this is a function call this particular
line over here and this is the return now you don’t need to care about it
unless you were going to do something with it so you usually when you’re
writing JavaScript or jQuery code you wouldn’t see this because I mean you
would just call it as an instruction rather than expecting a return value
from it right just in case you have a hidden field in your form then input
coolin hidden is the way to go pretty similar to text our password
field so I’m going to leave it up to you to try it out as part of the assignments
on your own but literally there is too no difference except of course the
hidden part next to the Select drop-down so basically a drop-down button and
let’s see how we can sort of play around with it I’m gonna clear this up little
HTML okay the idea is curves so let’s select it by the ID
and see what the value is okay so there’s no value let’s see what the
notes tell us so there is no value right now because we haven’t selected a
particular option the value was already selected so the idea was Kars
see we got the value let’s see how we can set the value so to set the value we
can just pass it something which is a value we want to set so this did not work because essentially
if you look at this right the value is not s capital a double a B the value has
to be exactly the same so if I do this and now I do this then it will be said
because otherwise it’s not this case sensitive so it’s not able to match if I
want to do an OD this wouldn’t work but if I do this this would work so you need
to really look at the value that you’re trying to set the option with the value
attribute and set the option tag so just in case you wanted to get the selected
index of the option that is true so let’s suppose you were making a form
which has a drop-down based on which you want to do certain things so you want to
get the index that has been selected so let’s again select and then we type slated index so it
gives us the vagus 3 because Adi is on number three in terms of number four but
it’s zero indexed so if we set it to this then I’ll change to one if we set
it to two the value changes automatically in the
drop box so for setting the value you use assignment and forgetting the value
you use this now of course there’s a slight difference in the way that these
things are done based on the input type that you’re dealing with and this is the
nature of things because selected index is an attribute over here and you can’t
exactly set the value like an input box so please do keep in mind in terms of
what you’re dealing with dot Val will work in a number of places but it might
not work if you’re dealing with a particular kind of input next is the
submit button in the reset button they can be used again so input coolant
subnet will select the submit button and input Col deze it will select the reset
button there are no essential values inside them
but then this is basically more for selector mention here that you can
select the submit and the reset buttons as well and then you can take further
actions on it what further actions we’ll see as we go along
so next bit is form validation so now once that you have the value of the form
you can apply any of the typical JavaScript checks for string equality or
anything else that you might want to check so way here if you look at the
example it’s a simple example where you want to check the name value is not
empty you want to check if the address value is not empty and we want to check
the email values not entry it’s not empty in case it is empty then we want
to reload see you so that hey you have left this particular field as black
please do for the top now the second validation is for a check box and the
message is going to be this so this is more for demonstration that if the
message is said if the check box is selected then a message will be set in
the HTML otherwise it will not be but the similar thing
it’s a morphic condition check rather than a validation but kind of builds on
the concepts that we just talked about regular expressions now these are very
very important and you will find them across languages not just in JavaScript
but also in languages like Python Java C++ Ruby anything anything for that
matter and they are commonly order checks as well and they’re very
important so what they are essentially to boil down is so C simple string
matching is very easy right that if you can check for an empty string but what
if I asked you to determine if a particular value was an email or not
that becomes a little tough so an immediate reply or that hey I will look
for the add the red symbol but then there are exceptions what if the user
forgets to add com so whatever the user as they remade as
instructor at the rate at you Rica so you need to check for the calm as well
but then there are so many domain names so what about it you cannot go and I do
record code or ten already rakat or ten should you not consider that as a valid
email so as you see there are a lot of complications when it comes to doing a
simple simple determination whether a given value is an email or not and that
is where regular expression comes to help it basically helps you look for
patterns inside a given string and determine if the pattern is there or not
so we as human beings recognize emails no matter what because we just sort of
understand the pattern that it has the computer doesn’t know what he knows
really are in a way so you need to tell it that hey you need to this is a
pattern that I expect the string to be in is the pattern there or not now the
weighted X’s are written they are written with certain characters that are
understood by the language is implementing them and what I mean by
that is that any language gives you the functionality of a regex
and the symbols that can be used are pretty universal for example this cap
though the first symbol the start of string so let’s suppose you say that my
given string should always start with alphabet a not in the middle not in the
end it has to start with a the sentence has to start with the end
checking for that that is where the carrot will help you let’s suppose you
want all the words which are ending with the little m and that is where dollar
comes up next is the period symbol which just matches any given character any
character that you see on the keyboard any valid ask our utf-8 value plus
refers to one or more characters so you might say that the name length has to be
at least of five digits or if you want to check or if you want to say that hey
this particular string should or the name should at least be one or more
letters that’s where the plus symbol who come in naturally your strings might
contain the dollar symbol itself so if you’re looking at an amount right $400
$300 or something of that sort how do you sort of give tell regex that he
ignored the dollar symbol you do that at the backward slash question mark stands
to 0 more characters so let me show you a quick demonstration of some of these
things other than just talking about it and there is a very helpful website to
kind of learn this I would recommend it to all of you to visit this website it’s
free x101 com so let’s suppose this is where I will
write a regular expression and this is where I’ll write a test string to see if
it matches go not and this is where you will get the match information I’ll
select as I said that there are multiple languages multiple flavors as they’re
putting it I’m going to select JavaScript over here so I’m going to say
identify all strings starting with the capital e so alpha beta comma apples
America trays yeah so do note that the
single test strength this is not a strength so if I remove this and it is
only matching at the starting of the string so it is giving this entire thing
as input not just this one so let’s suppose I remove this and there are no
matches let’s suppose I remove beta no Max is still because now the string
starts with G there’s a match efore apples so much
again because the string starts with the return because this is all the next line
now there’s not much again remove this then there’s a match again so this is
the ending of the string now let’s suppose the string has to end with a
certain character where it has to end with C so it can be anything but it has
to end with C so EB C matches and it can literally have anything in the right all
right like I’m just typing random gibberish
over here but as long as the end is in a sea I’m good the moment I remove it the
mass is gone you got a small C one for the capital C only the capital C will
work it can be anything it can be one two three four five seven eight nine ten
followed by the capital C that’s what this regex tells me now let’s suppose I
wanted a three letter word which starts with an A has any character in the
middle and then it ends with the edge so abh will work abb won’t work so
Dotson divides any character here for it should work
ehh will work aah polish will work so but to go back this is just a pattern in
description ok this is a pattern description that I’m doing and these are
the test drinks so if you understand what the pattern description is it looks
a little funny I understand that but if you just sort of understand the meaning
of the individual symbols right then how am i thing that this matches this
particular pattern for this match of this particular pattern description is
what I’m trying to say but this wouldn’t work because only one character but if I
add a plus in front of it then advance because plus was any number of
characters one or more characters they said that taught taught refers to what
type of characters plus refers to how many of them can occur so single dot by
itself will just be one character but a dot plus is me kind of writing infinite
dots between E and edge me saying that hey any number of characters meaning enh
will do it the mass will continue to happen as long as there is an edge here
as soon as this goes or just get small it’s gone so then the next is pesky
character let’s suppose I want to match four hundred dollars or I want to match
anything which sort of ends with a dollar or a surprise so I’ve need to say that $400 matches a
harvest is 500 for Diana or this was 100% this wouldn’t match but $400 would
match because this is ending with a dollar next thing here is zero more
characters so let’s suppose I had to say that a and then the character can be
there or it can’t be so what this will do is a little match eh I’ll of ABH race
eh ehh because the question mark is saying that hey maybe zero or more
character it’s different from class which says one or more characters the
question mark is more open that way so after this we have so alphanumeric
matches is the primary one that you need to look at where I am saying that okay
fit the square bracket we see inside it I’m saying that it should match any
single character inside A or B or C so it’s more of an all condition that the
match has to the string that you’re matching for needs to contain either an
A or a B or a C for it to be a valid string now this is anywhere in the
string in terms of point unless you tell it where you want it so if I want it to
be at the beginning and I say hey any letters which are starting with a B or C
any words sorry so this is valid
this is also valid also valid
right but this is not valid keep watching the match information over your
page from a test string then if I do this it’s not valid
so starting at any of a or B or C if you place a carrot symbol in front of it
this is within the bracket not outside it then you’re automatically telling the
regex engine that hey it could start with anything apart from this so it
really depends on which way you’re going whether it’s I felt a lot of characters
that you were to include or exclude depending on that you will make a choice
so if you are just saying that hey ABCD should not be the first letters then
probably second option is better than you know writing all the rest of the 22
alphabets as for the first option so if you were to say that write the same
thing in this way you would end up writing all the 23 other characters or
things of language this one is pretty interesting it says E – Z so characters
in the range lowercase e – said uppercase e – said and numbers so the
other ones are little plants what I would suggest is that you really try
them out and in terms of what will be used when I would what I would suggest
is that if you have already used regex then I think you pretty much know the
answer to that question but if you haven’t it will depend on the situations
at your end okay it will depend on the situation that you’re in and what really
helps is practicing practicing practicing so if you go on over here and
I’m sure you will be able to find some practice problems or I think your
assignments would have that please do practice the same very important that’s
the best way to learn regex rather than just memorizing a bunch of
rules just practice the rules and they will come to you naturally so continuing
with the sets in case you want a short form for any of those here are the short
forms so you remember we did this one and so it’s not exactly that sorry it
contains the underscore character as well but yeah it’s pretty close in case
you want to thought of only numbers then it’s backward slash D if you wanted any
non digits then talk about slash capital D if you want it only you’ve only words
numbers and underscore then it’s fab slash W which is kind of like
alphanumeric if you look at this is alphanumeric this is all non
alphanumeric and these are for white spaces this is for the spacebar so
jQuery provides us with the regex match oh it returns true if it finds a match
otherwise it returns a false so this can be intimidating to beginners the regex
given over here but if you do a rest your test against the email then you can
return true otherwise you can return a false so please do take note that the
sub fairly complicated regex I encourage you to try and figure out what it means
but if you don’t get it it’s ok however the thing to remember is that
red dot test is available it gives you a true or false based on whether it was
successful as a match or it was a failure of a match and then of course
you can use it in various scenarios – based on what kind of inputs you’re
getting what its presence context what is the business logic what is it that
your application does or what kind of validations you want to build next is a
very very important concept called event handling in JavaScript okay so
let’s begin so the first thing is that Sanskrit provides white sauce with the
dot bind function so in this particular example what it is saying is that T
whenever h1 is clicked on call this function that I’m describing over here
and let’s just quickly have a short demo so let me go to my file
and let me mute all of this out that you know clear playing field have a example or D set up for you guys
so there is a P tag and it’s a paragraph and I wanted to display an alert every
time it was created so I went ahead and clicked on it and whatever was in there
was executed so alert can be quite annoying so this is to a console dot log so you see
case than our of time it was called so instead of the annoying hurt statements
you know this is a better much much better option to use console dot log now
there are various kinds of events in JavaScript click is one of them but
usually somebody would not click on a on our paragraph right and you would hover
over a paragraph wait I’m sorry the event was mouse enter so this works on Mouse entering we’re in
Mouse entering I can also make it work on Mouse leaving so entering or leaving
is basically defined by so if the mouse is going towards the
element then it smells entering the domain of this element nothing is going
to happen if I stay over here right but I’ve had leave which I am leaving the
domain I’m leaving the area then this happens
so let me kind of demonstrate it better by giving it a child Oh for the one pixel solid black and let
me give it a margin of Texas sorry I think I have to give it a
pairing iPad so the reason I’m giving it padding is so that it’s like big and
there’s a cordon of area what is happening as I’m entering and
I’m leaving okay let’s do another thing let’s separate these out so we have
Mouse Center and we have House Lee in your world and this is entering your
world so that’s what bind does it ties in an
event or a user interaction so user interaction can be clicked as I just
showed earlier it can be mouse entering or leaving it can be key up key press
key down there’s an entire list of the same and these are events and this is
called an event handling so handling basically means that something has
occurred in the web page now how do you as a developer write a response to that
and the response is really written in this function here so this is what the
event is going to be and this is what the response is now one question might
be that how do I know what events are going to be there on the web page well
that is what you will describe as a product but okay on my web page the user
can’t enter it can use over affects the user can click on buttons see you can do
this or that I mean that really depends on you and and the business logic of
your application and based on those interactions you have to define your
response so in the sense that you might have the useful in apps that allow you
to do several things whether it is drag and drop items some are simpler that you
just allow you to click on buttons so it depends on really what you’re building
and that is how the events sort of work and in terms of your response to the
events can work out so another thing is this keyword is basically assigned
automatically inside the scope and it refers to the original HTML it refers to
this the JavaScript object on which the function was declared so we will just
see this shortly let me just show you a demonstration
you see click me is coming with entering your world because I just call dollar
this dot text so just picking up whatever is inside of the paragraph tag
now unbinding is a way to remove an event so sometimes you may have a need
to remove a certain event if it’s no longer required and I think it’s very
important from a man map from a memory management perspective as well and it’s
important that you remove the event just in case it’s not required anymore and
you feel that it can happen the business logic not recommended always but you
need to have a good use case we’re using an by it so let’s suppose after the
first time this happens I want to unbind mouse enter so please note it very
carefully what I’m doing here what I’m saying is that the first time it leaves
the mouse but the mouse leaves the P P tag then the mouse enter event should no
longer be applicable that’s what I’m trying to tell my jQuery let’s see how
it responds so now it only responds to leaving it has not responded to painting
this executed once and now as never execute this right again
okay exit entry nothing on entry on exit yes but not an entry because we didn’t
unbinding on mouse enter so unbind universally removes any event handlers
so this one was just removing mouse enter but if you want to remove all the
event handlers which is both this one and this one on the same element that
you want to completely disable any sort of response to the interactions this is
what you need to do now nothing is working both of them are gone so it will
execute once and that’s it now there is also the live method so using the line
method you can attach any event on low to your future elements which matches
your original selector now this can be a little tricky to understand but luckily
for us a bind and bind in live methods have been deprecated from jQuery version
1.7 now in case your project is still be using 1.7 then it’s a different case but
in case you’re starting a new project definitely I think you use the more
latest version of jQuery so let’s look at which version of jQuery is currently
active so right now we’re on version 3 so if you’re using 1.7 it’s really
really old and I strongly strongly recommend that you figure out a
migration path from 1.7 to something like 3 so 1.7 would have come out a
couple of years ago and strongly recommended that you do not do not use
these methods as they have been deprecated now on page 2 pretty much
like works like mind there is not much difference in terms of how you define it
and work with it but I think internally jQuery would have made some changes but
yeah own works in a very very similar way now as I showed you with bind you
could add multiple events to the same handle but one interesting example is in
case you wanted to create different responses based on different actions
instead of creating two different bindings like this what you could do is
that you could simply say that hey I wanted you can pass it an object
and you can say that a loss enter I want to do this at all mostly how to do this so let me go over the color box so just
a simple HTML box described over here so let me describe a span class message I leave message color is right font size is let’s set it
to 16 pixel and we’ll do nothing but simply to go to
I’ll pick up the message you okay I think yeah I think sorry this is
bending it over here it’s mouse enter with the EE please take note of that they’re stating that when Taiwan is not
just changing the last bit which is that it seems like that let me just remove it
so that it’s very clear that exchanging the entire string and aren’t just a fart
which is different thank you so I mean it’s not too different but
it’s just cleaner this way it’s very very clean oh this way if you kind of do
it like this so I would recommend in fact looking at this and this is just
like if you look at the syntax might look confusing with all the girl you
braces at but then it’s just a JavaScript object which has three keys
corresponding to the event names and having multiple handlers for the same
next is the event object apart from the fact that a click or a mouse intern or
mostly will happen there is another very one very important thing which is the
event object now whenever the event happens you might require additional
information about the event this is passed to you by the event object which
has several attributes one on the mistype so let’s suppose you had
multiple events so in the sense that if you look at this particular way of
writing things where I could have written it like this as well right now
then you need to know which event has happened and there suppose you wanted to
you do not want to do what I did over here you didn’t want to create multiple
conditions because what you want to do was that you wanted to do one thing
different based on what the event has been just one thing the rest of the
steps have to remain same they suppose so then you need the type which gives us
the button or key that was pressed target gives us the originating element
and x and y gives us where the mouse was when they haven’t happen where exactly
the mall source and certain examples of working with event objects is that you
can check if it happened on a particular place or at a particular position and
you can take a decision or you can write logic accordingly so let’s quickly see
what we are getting as a result for this one
so right-mouse leave was a function that it captured and the position is zero
zero is is more like in terms of Dom where is the elephant then the element
or itself and then the mouse position 267 355 so target is this which is this
particular thing and mouse leave is the event dot type overall if we do remove
these and it should we just do this we can end up with something like this and
if you see it’s a very rich sort of object with a lot of things inside it’s
not that you need to know everything today but I think certain things that I
mentioned over here and the slide deck are definitely definitely useful for
seed event event dot which and so on and so forth so let’s suppose you want to
override the way link works let’s suppose clicking on a link what you want
to do is that you want to display the webpage in an iframe on that page itself
or based on a button click on a form you want to add certain validations from
your end so you want to use the button time but then you don’t want to for it
to submit the form as it may be you want to make us different kind of request or
you want to do something else with it so that’s what preventdefault does it
removes the regular behavior of the particular thing that you are trying to
target let’s try it out let’s call it target link
holidays Jessica Lewis GPS google.com let’s call it target is equal
to go blank then let’s call it as a target link
maybe we do bind the click event to it and then we will to say that a so if I click on it now nothing happens
it’s not that the link is broken the link is fine Google is opening up
this is that on this particular page after five change the default behavior
so this can be quite powerful I mean imagine that you can take the a tags or
you can take the buttons and you can use sort of override certain behaviors out
they have a default and this can really help you in creating really customized
websites that are serving a particular kind of effect that you wanted to have
based on your needs this was about amend or prevent fault now there is another
one called stop propagation which refers to something called an event public now
sometimes when an event happens right it might trigger events all the way up to
the door so if we look over here P I use the star selector right which is going
to be triggered on click let’s suppose I store the star we have a development
right and the dev element has a click event but subsequently all the children
of the div also or a child they’ve has a click event but then you
don’t want the parent div to cast that event because the event bubbles up so
that’s where you will use something called a straw propagation now this is
very useful if you are studying something like angular and this will
really really help you over there so understanding event bubbling is very
very important now there is another function which is kind of like bind and
bind so you saw how I unbind it a particular event right now what jQuery
provides us with is on and off but then if you think that it’s a little tedious
right it’s a little cumbersome that one you will once you will set the event and
then you will turn it off in a separate line you can use something call as one
what this does is that it runs the event only once and the next time you click on
it then it doesn’t on it so if we come to this one and I say that okay direct ones close the page that’s it now
no more Ranma if it was on then it will run multiple
times but the moment I changed it to one then it runs only once now off does what
unbinding did very simple I will just change it to one I’ll come here and then
I’ll do it although this dot off I suppose I wanted you to move on the bow
Center right I did not want to remove a sleeve
so what I’ll do I don’t know the page now it only runs when I come out of it
not when I go ahead that’s running now from now I can also part multiple values
to this so they’re both are disabled or if it’s
not I want to move all the events tails like this now this works in a similar
way as unbind and as the last I mentioned it’s a best practice to ensure
that you only have the event bindings that you need so in case you don’t need
certain event bindings the best practice to remove them because it really really
complex applications and I’m not talking about single simple applications don’t
want really complex applications is a lot of events and a lot of listeners it
might be best for optimal performance to kind of remove certain events after they
are no longer required so in case you’re removing a development maybe you know
sort of a way to offload the Dom element or hide the dog element would also be to
remove the events alongside it so let’s suppose you’re hiding certain buttons
but the events are still attached right and I suppose you have thousand such
buttons so it would make sense to unbind those events to avoid any sort of
unexpected outcomes so please do keep off in mind now another thing is that
you can trigger events on certain elements using the trigger function now
it can be used to mimic browser events just clicking of an anchor tag now this
is very useful think about it let’s suppose what I want you to do was
I I wanted the link to work right when I the color walk prevented the
foreign behavior you right so this where I wanted to mimic the browser
behavior so this doesn’t actually open the link is not an actual click on the
link but it mimics the behavior and I can observe certain things using this
and I suppose we look at this example and what it does is that it sets a
function called foo on on the B tag and clicking the function will call that
they’ll execute it but the trigger is elsewhere instead of the mouse it is
elsewhere the trigger is happening from so this could also be on the basis of
let’s suppose the user enters a certain input and you want to trigger certain
actions then it’s not just like I mean without any user interaction that’s the
main part here or you want things to happen in a certain way that’s where dot
take away with you out and finally custom events so the way custom events
work is that you can create your own event name and then you can trigger the
same by using the trigger one so squeeze can be anything essentially so let’s
suppose custom event what does it do is because I read called I want to call it straightaway so one question that you might have is
wherever I use this C so it will be useful if the website is really really
interactive where you have exhausted all the existing events and let’s suppose
based on certain positions of the mouse let’s suppose be him the position of the
mouse you want to trigger an event and you can’t call it any of the other
events because it creates a conflict of some sort and you want to call it your
own custom event specific to your applications that’s when this would be
useful see the custom event was called immediately as you reload the page
because I’m just calling it here from outside I’m just calling it here from
outside I could also call it here so another thing I could do is that it
would just click on the link but you will notice that the customer event was
called then I page open but the customer event was also called so let’s suppose
you have to track the number of link clicks this would be a very easy way to
do that right so you could let’s suppose track links and you could call it over here Lake was triggered and the custom event
was called this one is example I sort of suggest that you try it out and see how
this works yeah already done removed laughs at an ad class so this would be a
really nice assignment for you so do try it out and see how you can
sort of use it but in terms of custom events why they would be used I think
it’s more it’s again about customization of your application to an extent where
you know it is making sense because it is out of scale so this will usually be
used when you are at a pretty decent scale in terms of the number of lines of
code that you have written or the amount of like the breadth of your application
that you have developed so prior to a charts so easier 50 asynchronous
JavaScript used to sort of exchange data on the Internet
now prior to each acts everything was done on the server side so whenever you
would click on a button it would reload the entire page but think about it today
when you like something on Facebook or you comment or the Facebook newsfeed
it’s more data you need to reload the page every time no right that’s because
each arc is the magic behind it which can make calls to a server and by server
I mean through a URL so it will call a URL secure URL and either get some data
or send some data to a web server the benefits are that the user thing sees so
this entire process is much faster than loading the entire website and again and
again so loading the entire website again would mean loading the HTML CSS
and JavaScript files again it’s much much faster because you’re just getting
the data that you need and you’re updating using javascript so you’re
saving on a lot of time and then all major browsers started supporting
something called as an xhr XML HTTP request from 2003 and that kind of solve
this issue because now if all major browsers are supporting it then it
became very popular and now you see it almost everywhere when you take almost
any action from technical chart message to let suppose liking something or
subscribing to your favorite YouTube channel it’s all being done by our Ajax
so whenever you see the page loading but some sort of data being
exchanged on the internet it’s Ajax which is helping you out so as the first
line says it can be transferred between the browser and the server that is the
client and the server without having to reload the webpage now how is the data
exchanged this happens by a URL so essentially all urls as we know are
exchanging or carrying some data as a response so when you go to facebook.com
or google.com the response is an HTML web page right and when you play suppose
you have a link to an image on the web it’s a URL but then it’s responding with
image data type so similarly you can have any sort of data at the end of a
URL and you can load the data or you can get the data or you can send some data
to a particular URL for a particular action and this happens through Ajax in
JavaScript through XML HTTP request API in in JavaScript and Ajax is something
which is very popular that way now the requests are asynchronous which means
the rest of your code continues to execute while the request is being
processed and the response is received in XML format now this was when it was
back in 2003 but now of course as you will see you can sort of specify any
type of format that you need and entire technology piece this entire process is
refer to as asynchronous JavaScript and XML
now XML is a bit dated because today xml’s are still used but not in any new
and upcoming system in terms of for exchanging data so XML is something
which was very popular back in the day but then because it is so bulky largely
gone out of fashion but the main things to remember here is that the rest of the
code continues to execute while the request is being processed now this is a
very powerful idea which means that you can have multiple Ajax calls at the same
time so in your Facebook page loads right your newsfeed is being loaded your
friend list from the charts has been loaded any training stories are being
loaded ticker is being loaded multiple individual requests happen at the same
time while the page loads and this makes the entire process seem really really
quick because at least you can start seeing
some of the content some of the data while the rest of it loads so you might
have observed it sometimes you know the ticker hasn’t loaded or the friend list
on chat hasn’t loaded but everything else has rooted you can like comment and
the other one is still loading and this happens because they’re asynchronous
they don’t happen serial in a serial fashion they happen in a parallel
fashion now you might be wondering if this is some way similar to the concept
of threading that you might have seen in something like Java or any of the other
languages which support reading so it’s not threading it’s something that the
browser enables with the use of something called as an event loop
however it is really topic which should be tackled by much advanced JavaScript
isatis what is an event loop and how does it work
however it is a very popular interview question that if javascript is a single
threaded synchronous language how is it that you have something called as ears
acts which is asynchronous which is parallel to everything else now
understand that JavaScript and itself hasn’t changed here it’s not that the
rules of JavaScript have changed for this particular thing it is still
continues to be a single threaded synchronous language however browsers
enable this asynchronous behavior it is based on the browser so if you notice
the last slide mentioned something like in 2003 they started supporting it right
so browsers had existed even before that there was Netscape there was Mozilla as
well I think but then browsers support for this
started coming from 2003 and then it became popular so it is not JavaScript
which is sort of supporting it the XML HTTP requests API is a browser API
meaning that so if that sort of sentence is not clear to you it means that the
browser enables take Ajax requests yes you do it through JavaScript but then it
is certain fundamental things there is a foundation okay there is a foundation
that the browser is providing for these to be even possible now naturally when
we talk about the browser enabling it right there and we face the same problem
that you talked about in the first class itself that different browsers are like
different painters or different people and they implement the functionality in
their own way so everyone has a different XML HTTP request API that’s
why security comes in such a beautiful way that it provides you with single set
of methods which take care of requests across browsers as you will see as you
go along but this is one of the most again makes jQuery so so accepted as a
library that it helps you manage JavaScript related cross browser
dependencies and apart from dollar dot Ajax being a method there are certain
other methods available like dollar dog cat or a dog script dollar dog get JSON
dollar post which are also available to you now there are two more most common
methods for sending a request to a server one of them is get the get method
is used for getting any data from the server so this may be a search result
that you’re trying to get it may be a list of friends this may be a list of
notifications this may be a list of stories may be a list of videos on
YouTube this may be a list of channels on YouTube this may be a list of
restaurants so anything that you’re trying to get typically your search
could be any information that you’re trying to access an article that you’re
trying to read on a blog a set of images or gifs post request is when you’re
sending any data to a server and asking for it to be updated or created so this
is creating a signup form this is somewhere around updating your profile
in facebook this is somewhere around creating a post on Facebook this is
around creating a comment so Kett is reading and post is basically creation
or updation as required now when it comes to dollar OT Jack’s Jeep Willys
Ajax method there are certain options in terms of what kind of data types can you
exchange so you can start with something as simple as text you can just simply
transfer strings you can also transfer HTML imagine a web page which can just
simply load a part of it part of the HTML from the server seems a little odd
maybe but suppose for a second that the HTML was coming from the server there
was some updation there was some request based on which the
response is an HTML block you can also pass in this script as a data type to
add more scripts to a particular webpage then there is of course JSON the very
very popular JSON format which looks like an object in JavaScript that can be
used then there is JSON P so JSON P is basically used when you are trying to
load data from another domain we will come to this and then will be more clear
an XML basically follows the XML schema which transferred data in any custom XML
format but please notice that these are pretty much exhaustive in terms of they
allow you to exchange any kind of data almost any kind of data by using Ajax
functionality talking about JSON P so there is
something called as a same origin policy so same origin policy says that if
facebook.com/ it’s making a ajax request it should be making the Facebook the
request to facebook.com server in itself like the server’s domain name the
protocol HTTP or HTTPS or FTP or something else or something else the
port and the domain name cannot be different so it doesn’t mean the web
page needs to be different but it means that the person who sent that HTML CSS
JavaScript file is the same person we are communicating with this is a
security practical most browsers execute it very strongly now what if you wanted
to get data from another service provider I suppose you want you to get
eater from IMDB for your website but your website is not imdb.com it is a BC
or ad Reaper com how would you do that for this there exists something called a
this JSON P that you can make each ask request from different domains so in a
case of JSON P the provider or the service will respond with something with
a script that can be loaded into the page using a script tag and that script
will include the Dae requested robbed in a callback function you provide so it
just basically circumvent that limitation by kind of providing your
script which contains the data part of course this is not handwritten this is
more or less generated on the fly so that the script it will have a
certain string format that’s so work scripting language PHP or Python or
whatever it is must be generating on the fly and JSON P is primarily
when you want to make requests which are cross-browser requests
now there are various methods available in jQuery to make Ajax requests and but
however the Ajax method is mostly preferred and it is considered to be
good practice and it is a powerful method with a lot of features with a lot
of options available to create Ajax requests what it takes is a configurable
object so configurable object meaning the steppings or the options that I just
talked about which you can set and use to complete requests using Ajax now we
will go ahead and explore so you can of course go and explore all the various
options so let me just open it up for you so that you can have a first-time
view so we’re going to search for jquery of you can search for a zag
to query charge you will notice over here
these are the various kind of options available so yard there is a lot
of them not that you need to use everything to make your first or pure
initial exact request but it’s good to know that there are a lot of options
available because naturally I mean it allows you to do something in a better
way or something that you thought that you could not do but once you see that
option is available you can use that particular feature of the library and
really make something interesting out of it
so moving on some of the options available one of them is async so a
thing by default is true this is the asynchronous so you can make synchronous
is actually quests as well now this can be a tricky question in an interview but
the interviewer asks you hey can you make a synchronous JavaScript Ajax
request yes it is possible but it will block the execution of code until other
responses received what does cache – so cache is basically
it caches the response of your Ajax request and if it sees that you’re
making another request of the same kind it will not make this request again
instead it will handle it internally complete is a callback function that you
run when the request is complete regardless of whether it was a success
or a failure whether the request that you made let’s suppose the URI did not
exist or the URL returned or error 500 so it’s a four oh four or a five hundred
or or something else which is an error code or the request is complete that it
returns success 200 however complete says that no matter what the outcome is
once the jquery call is finished this is what you should do so one typical use
case could be less suppose you want to show a load or you want to show a simple
loader bar that when the Ajax request starts you want to start showing this
loader bar once the request is complete you want to remove the loader bar right
naturally which doesn’t depend on success or the failure of your function
it just depends on whether the request is complete or not if it’s an error
request fine but still remove the loader the next is data so any data that you’re
sending whether it’s with the get request –
if I the kind of query that you’re searching for or whether see the post
request containing the data that you want to submit to the database that’s
what will come in this parameter and again the value has to be an object
typically typically it is an object but of course it can vary based on the URL
configuration and everything on the server side but then one of the better
practices is to kind of talk in JSON itself so if it’s a objects a JavaScript
object then Ajax will basically send it across to the server like a JSON so then
it’s basically a JSON API that we are talking to next is data type which
specifies the kind of data that you expect from the server Bridgette specify
the kind of data that you expect from the server
next use something called as an error now this is that paragraph function when
there is requests ones into an arrow next to JSON be the specify the callback
names send in a query string and making this on request and the default is just
callback truck chef this is the function which is called when once the request is
complete and everything is has been completed the status code of 200 has
been returned and now you have the data that you needed Nexus timeout it
specifies the time in milliseconds to wait and consider the requesters of
failure so if you specify that here just wait for a thousand milliseconds this is
like one second but after that if the response does not return you should
consider that your questions of failure let’s suppose that is the kind of
application you’re building the time out helps with that type is the kind of verb
that you’re using on HTTP whether it’s Gator or post or support or a delete
default is get now you are this is the request URL of course so nothing happens
without this it is a mandatory option everything else is just mandatory
configuration or key everything else is optional so let’s do a quick example
okay let’s do a quick example I have here an eject function
in fact let me change this right you so you see this is like a JavaScript
object this is a JavaScript object and I’m just considering it to various
parameters complete with error with success and data and we can also mention the type as get
this be explicit about it then mention the datatype so I’m going to make a JSON
request for this demonstration what are the parameters can be used let’s use the
timeout as well let’s set it to 2100 and
okay we are good so which one comment this now for the URL what I’m going to
do and I think you guys can try this out as well whenever I have to sort of try
out something and I need like a JSON URL this is where I go so you can just
create a JSON for yourself over here you ways to creation we have gotten our
access URL over here we can also view the JSON it’s a simple JSON nothing much
and we can pass the URL over here let’s take this page for a spin okay so the button
peering over so in case you are not there’s something called it the network
tab so once you open the debugger right there is a network tab it’s very very
useful for specially for Ajax requests it has something called as an xhr this
is where you can see all the Jax requests that your web page would ever
make and this is not just for yourself this is for this not just for your
website this is for any website that you go you can go to a youtube.com and once
you open the network tab and you look at xhr you will see all the requests that
they are making let’s click on the button so automatically we see a request
was made right if you see a request was made and you got a response
same as this except that you called it tearing jQuery let’s go get the console
completed success and data and then complete has been called over there
now let’s kind of change the URL a little bit so the request will fail I
just it was anyway the seven I removed the seven
now let’s reload the page and click on let me now this fails but it completes
with arrows so why is this important this is important so that you can handle
the situation so I can sort of let’s push through an arrow here looks like
something went wrong to this please try again later so they of course
have a similar request of course they are getting the data and then they are
sort of setting in HTML I leave it up to you to try it out reach out to support
if you have an issue but it’s pretty much it so the I should and load
statement is that they have shown something in the HTML and yeah this
should suffice let’s look at some of the other rejects
methods available so one of them is dollar gate so in fact I think we can
use dollar gate for this in itself so we’ll do what Allah gate over here GSR
and the URL needs to be it can be the same URL and it has this function which is
basically on request completed and the same tree object is basically
any of the data that we want to say but in this case there are no query
parameters so we can just get by without it and this over here is the server
response so let’s try our dollar get what I will do is that I will mute out
the original Ajax request and then you can try this out like I made a syntax error let me see 9:54 you so as you saw we can’t just simply make
the request like this let me remove this and this is now going to if you dollar
that get and this world are perfectly fine for us
and now we have had in the console the request completed variable has been
printed and same is available to us that I was making was the key so this
does not take an object right and this one will work now I was just trying to
patch it up in it doesn’t take a key and it just takes the parameter that’s it’s
a mistake just engaged please remember it doesn’t take object like Ajax does it
just takes the values in case you already know that it’s going to be a
JSON request you can try something called escape JSON or you can simply
possibly URL next what you need to do if you have a look you can pass the data
object and you can pass the response the response here is simple it’s going to be
a function and we will say control dog loaded
I think I made a made a spelling mistake yeah it’s kgs on ortho cup too
and we see it on the console that’s using JSON and we can see the request in
the turbine in case you missed it let me show it to you again
now we’re calling using get JSON similarly there is a post method he used
slightly the data values he passes the function and you specify the response
that you’re expecting now there is something very interesting called as
dollar dot hood this stretches an entire HTML from a URL and let me just quickly
show you what to do with it so I have a container div here and I just test or
HTML it just contains this h2 turns so it could contain any issue but just
contains this now what I will do here is that I will try to load the test or HTML
I would try to load the test on HTML and into the container so let’s see how we
can do that he to this and voila now why this is so useful is that it allows you
to sort of have components i’ve defend you reuse different pages different
sections of your HTML in multiple places so that’s why this is very very popular
and interesting as an idea that you can make smaller versions of HTML file with
reusable components and use them in multiple places by tying it together by
usual colors dot load moving on so serialization and Cyril RA so what she
realized does is it he realizes the form straight into a query string and they
input element must have a name attribute to get say tonight so you cannot if the
input type does not have that the name attribute then it can’t get serialized
but if it does then this is a way to serialize it this is specially useful if
you make submitting a post request to a to a server where you want the key value
pairs you want to tell the server that hey this data is this particular value
right otherwise how would sever know that if it is the first name what is a
full name on to the last name or if it is the middle name I suppose you would
making an operation which took the name of the users
so first name last name it to be proper and if you store them accordingly so
that they use it accordingly everywhere so that why serialized can be very
helpful to utilize re is similar to utilize but it produces an RF object
instead of a string the serialized produces of strange but finalized I
reproduces an array of objects which can be more useful depending on how the
service iris confident so what I’ve done for these is that I have the jQuery
website in itself has a very very good demo of this so I did and I’m gradually
demonstrate the same from there right so if you come here what we have is you
have a form which other multiple input so let’s select one input let’s not
select any check box and let’s select both the radio buttons so if you see
single is equal to single to multiple is equal to multiple to I can also select
this one so multiple people multiple an but it’s going to be multiple to and
radio is equal to radio to I can also select the other radio button should
make it radio why I can still check one makes big check to so this is really the
output strength the way it is happening is that this is the input form this is a
form over your right let’s have a look at it based on the changes so Donna
select based on any of the changes on any other input boxes show values is
being calls if I change any of these input boxes whether it’s the drop-down
or the multi select or the checkboxes or the radio buttons it will call this
method called show value or show values does is it takes the form object it
takes the dog the next entire thing and just call serializer nice that’s it
that’s it and it gets the string it gets the string and it appended to this
results at we switch so that we will be able to see here so as simple as that so
instead of you know taking all values one by one one by one by one of
selecting every input now you have a very very cool method which will
automatically get the values for you in a string but just select no form or
option and calling serialize method on it have a look at here lies array and
few lies re the example is pretty much similar however the execution in terms
of it’s a bit neater I would say the it maintains an ArrayList and I mean
I’ve got better string artists tend to be small easily many pollutants so we
have used the Chico at each function you passed in the fields which is basically
the re so look at this flying foot nine and we write read over it and just
display the results over here so Dean is pretty useful if you’re submitting data
to to a server using the source request now coming to jQuery utilities so dollar
not each uh something that we have already started in the past it just
basically takes an array of values and I trades over them one by one one by one
one by one so we can just take an object or an array and pass on the qidan values
and they’re suppose from the entire thing so it’s a very easy and convenient
method and I would recommend using it a word the Carnation for loops it just
makes your code look a little more neater and organized as compared to you
know writing a for loop of course I mean the thing inside it wouldn’t change much
but then it’s just much neater and it’s much more robust in my experience with
large applications then using something as a for loop almost everywhere and of
course I mean in jQuery you can select an entire set of elements and then do
something on them so in case you wanted to I think you could just like get the
links the value of the links inside each of the you get me that are a tag with
this snippet of code it will I trade over all the Li elements get the snippet
of the e-tag and just consult or log it next is map now map is is very very
useful let’s suppose you wanted to take an array and you wanted to create
another re out of it we just contain the capitalized words so you want to take a
list of names you do not want to change the original one but you wanted to
create a new one which just had some sort of modification or alteration to it
that is where dot dollar dot map comes in if you notice over here
it takes the names Molly and Libby it I trails over the names and per name it
does a split on the space and in case it contains any
it will speak to split them and present you with as I record has exploded girls
kind of funny but yeah that’s what dollar dot map does and again one of the
more robust ways of dealing with things dollar dot trim is simply a trimming
function so I could show you a small quick demonstration over here so we take
all this so it removes the initial and the ending
space not the space in the middle but it removes the space in the starting in the
DNA it’s just something that helps and you know it’s a utility function so you
might need it to kind of trim the user input before sending it to the server or
you might need to just you know clean up data that you’re getting on the server
because it’s corrupted or not corrupted but you know it’s is not kept neatly so
that’s where it dollars or trim will help you out next is in array check if a
particular player limit is in the array or not now of course there are other
methods to it in JavaScript as well but then this is just very utility based
function available in jQuery so we can call in array and we can say for and
then you can see here are our and it will return negative one if it’s not
there if it is there then it will return the index so it’s basically returning
the index okay so the condition is really to see whether something is an
area or not if you have the end result of this is greater than negative one
then it is true if it is not negative one I suppose you’re checking if 100 is
in diary then it’s false now then there are some other utility functions one of
them is called is function so you can check if a certain thing is a function
or not quite interesting right so let’s try it out you know in a fun way
so it’s called is function on dollar dot each and it’s true is hollering array
here a function yes it is jQuery it’s use a function we all saw the window
object without a function no it’s not a
function it’s an object if we display something like this and then we called
all of its function on a it’s false so just a convenient method of checking
something if of the type that is something is then
next we have something called as a is plane object so what I described as just
now where a we can also try it on the window function is plane object so it’s
not a plane object let’s try on a so European object windows a non planar
object but he is a plane object who are here in this case let’s try that out on
dollar dollar is not obtained object jQuery is not a plane object let’s see
if – all about his axe Colorado Ajax another plane object but it is taller
dot Ajax our function yes it is so daughter of Ajax is a
function similarly you have something for checking if something is an array or
that would work in a very similar way so the next topic that we have to tackle is
something called as a deferred object or deferred concept in JavaScript or in
jQuery however before I go over here let me introduce you to our problem
statement okay so let me unmute this let’s suppose to say put LED and over here or what we are
going to do is you’re going to take the user details and you’re going to give it
the value of the result so we are going to face the details from the web and
then we are going to right now what I’ve done is that I have
called the Ajax and after the Jax is called just are the exact statement I’ve
also placed console dot log user details nothing for a second what do you
expected to do initially user details doesn’t have any value then I made an
ajax call and then i’m trying to print it on the console the details what do
you expect and just hold your answer with you whether you won’t expect it to
print the details or whether you expected not with the details and then
assuming that you have decided what did we do let’s see what it will actually do
let me reload the page clear up all of this so if you look at this 952 it says this
is undefined this is undefined but once we look at 41 this says that it is
successful so what happened because right we called
the Ajax treatment and this seems to be have been successful I mean the network
tab states that that it is successful we have the data but then seems like we
went wrong with something so here is the thing
remember it’s asynchronous so the way it will work is that JavaScript will call
this and then move on to the next line JavaScript will call this and move on to
the next name then when the response comes back from the server that is when
JavaScript will execute this function so it’s asynchronous just happens this
entire thing gets executed after the request has been completed successfully
so you will always see a console dot log as user details as undefined over here
this is not like a mistake as such but this is basically not understanding the
concept of ajax web now a lot of times when you’re dealing with complex
applications or not even through complex application but anything which is more
than you know at an industry level you are going to deal with these situations
where responses will determine so a particular ajax call might happen and
the response of that each acts call you want to do certain other things so how
do you manage all of these things because if you are waiting for that
quest to resolve so they suppose what i was supposed to do is that i was
supposed to get a list of movies from IMDB by our API call and after I got the
list of movies wrong IMDB by an API call I was supposed to pick the movie which
is more than two hours long because the list of movies also has a duration of
each movie after I find that movie then I need to make another API call for the
list of actors then I have to make another API call for the list of actors
then if the list of actors has Tom Hanks in it or has any particular actor with
the letter T as the first name forget Thomas litter t as the first name for
those actors I needed to get details in individual API call so these are or URL
calls right so the first is for the list of
movies then based on some condition we are asking for the actors in it in that
particular movie and then on another condition which may be just the names of
the actors or the name length of the actor so basically we want to get all
movies which have all actors whose first name starts with the letter T and have
starred in movies which are more than two hours long I know it’s not a
imaginable scenario but for the sake of understanding you can assume that this
is something that we want to do and trust me in business logic in case
you’re an experienced developer you would have seen more complex cases than
this but if you are an upcoming developer this is not going to be
surprising to you once you have been working in the industry for three four
or five years so how do you deal with this of course one answer is let’s
suppose I was supposed to do something with the result so let’s suppose if I
had some conditions over here and I to make another Ajax call so I could simply
do this follow each acts right I could write another Ajax call and then
within that I could write another one called a success and I could write
another one and then it goes on and on and on so one
naive way of thinking about it is or basic way of thinking about it is that
hey there’s an AJAX call okay when it is successful I’ll make another one then
I’ll make another one I’ll make another one but then you need
to really at some point ask yourself hey where does this end because this is
going to be very very difficult to debug let’s start with that this is going to
be massively difficult to debug find the errors in this if even one ejects quad
is going wrong you’re going to go through so much the second thing is this
kind of situation actually has a name in JavaScript it’s called callback hell so
in no lesser terms you know Barney and tune down terms it’s called as callback
hell and it is hell in fact if you have to debug something there’s a lot of
complex business logic and built like this so people in the JavaScript
community saw this as a potential problem because the situations with the
upcoming complex applications that were coming up every day this was just blake
bound to happen I mean you see so rich applications on the web for the Internet
today this was bound to bound to happen now they came up with something called
as a deferred object so it typically starts in a pending States now we can
identify with that right dollar dot e jack starts in a pending state where
output is not defined yet we don’t know if it is a success or a failure so in
the sense that when I told you that hey I’ve done up and sold hot rock over here
the Ajax call had been fired but we don’t know if it was completed so it’s
in a pending state the request is being made we don’t know how the server is
going to respond yet and the deferred object has basically two important
methods one of them is called as a result or a reject in jQuery AJAX method
will call resolve on the deferred object and it returns when request is
successful and it will call reject when request is a failure and both resolve
and reject can be manually executed on any manually created deferred object so
the way you need to think about this is that internally inside this Ajax
function so that suppose for a second there is something called as function
each arcs in jQuery right written exactly like this which takes something
calls and options now what what they would have done is the deferred object right sorry I’m mr.
Capaldi so this is a pseudo code for how Ajax
function might look side of jQuery code base now this is
something that they would have done then they would have called something make
the request etc now once the request is complete what they would have done is if
it is resolved option start success would have been called like this and if
it is a rejection REO either would have been called like this
now you see how this is sort of internally working that you specify what
is to be done but when it comes to actually making that happen this is how
it would have happened internally where it’s a deferred decision they don’t know
yet now when the response is there they would either resolve that initial
request or they would reject it and when they’re resolving it or rejecting it
they’re going to call the so this is an object right this is their options
method options the options one which is coming in the options parameter and it
has the success method defined on it or it has an error method defined on it and
it’s basically telling it that hey when the resolution happens you need to call
the options or success method if the rejection happens then it calls options
dot error method deferred object also has other callback functions which are
called as done fail or always and it also allows you to listen multiple
listeners to e Jax events without Manly calling chaining callbacks
so chaining callbacks is something that I described earlier to you it’s very
very useful in that way where it allows you to have multiple listeners to e Jax
events and doom to respond to scenarios in different ways based on what you’re
getting now in jQuery you also something called the promise and it is based on
the deferred object so it is derived from the deferred object but it is not
the deferred object okay it is a subset of it one way to look at it is that it
is a read-only deferred object you have the methods to attach callbacks but it
does not have the metals to resolve or rejected so one way to look at it is
that deferred is the producer it is what actually does the work so it is what
would actually make that Ajax call right wherever the deferred is defined but it
would return a promise so that function would return a promise in the sense that
this would probably return something called as request dot promise now promise is the consumer so promise
is what decides what to do when the function is returned so let’s take an
example let’s suppose you need notes for a particular exam from a friend so you
call the friend up and you say hey can you give me the note
the friend says hey I make a promise I will get you the notes so now you have
the promise it’s not that the friend has the promise the friend has made the
promise so this is a friend making the promise ok now whether the promise
succeeds or it fails the reaction will be yours but there is nothing that you
can do to make that request of notes from the Train succeed or fail I mean of
course you can give them incentives like I’ll give you a treat if you get to the
note but that’s real world but over here you’re talking about is that in an ideal
world scenario the friend they suppose a friend has to get the notes xeroxed to
give them – you already have to get them from somebody else but he has to find
them so the actual work is done by the friend now if you get the notes if it
resolves then your response might be to read the notes if it’s rejected your
response might be to call somebody else but the friend when it receives a
request it defers it deforest it basically in the sense that he doesn’t
have the notes immediately you just called him up out of part of the blue
and the person doesn’t have the notes immediately and he says ok I will get
them for you so this is not a scenario of hey can you give me the notes and
they hand you over the notes it’s not that scenario if the scenario is hey I
will give it to you I promise I will give it to you but if maybe not
explicitly they say that but they mean it right it’s a promise yeah I will give
you the notes and they say that they will give you the notes that’s an Efford
situation it’s deferred until and unless they come
back to you it’s differ so that is the big significant difference and promises
are useful in terms of they’re limited in terms of what they can do so in that
way you are clear so as is it of the what is your response
so in jQuery to tolerate the exact method returns a promise it has three
main methods done feel and always so what I can do is that for
this one I can call done I can say
okay let’s do a control dot log of user details let’s try this out
and it worked it worked on line 69 now you may be asking here but I could have
done the same thing over here that’s just because I’m doing a console dot log
but remember the original example of callback hell now this is a good place
to kind of call another Ajax function this is a better place to call any Jax
function that then this will ton then you kind of do this then you call the
next three jacks call there is also fail and then there is also always I this
Clearfield this is the default callback for any rejected requests and always is
is called always no matter what so this is a simple example pretty much similar
to what I have been showing you so you call a function the Ajax response and
then you can sort of individually go out and set these this is much cleaner to
read I mean of course I was attaching it that you were here but I could have also
done this okay so now this is a request and I
could have done this so don’t take this lightly though in
case you’re thinking oh this is just about readability
but readability matters quite a bit imagine working on a code base of ten
fifteen twenty thousand times of code it will spiral out of control really
quickly it’ll spiral out of control before you can realize that so that wait
it is not that you can’t survive without something like there further promise as
a concept you can and I’ve seen people do it however much better to kind of
learn these things and do the best then there is another concept they suppose
I’m making so I’ve been making this Ajax call again and again and again right I’m
making an internet calls there is a concept of caching where you want to
save those result they you want to save the result of the outcome now what you
want to do is that a very simple cache technique here is that you have made a
request and you saved the promise as a value in a object so forget everything
else what you have simply done is that if you’re making the request for the
first kind if the ID of the request in the sense that they suppose I am loading
songs by IDs which I one two three four a building five songs and the song one
hasn’t been loaded yet so for the first time this condition will be true so I
want to store the promise I’m just storing the promise I’m not storing any
results I’m just doing the promise of this outcome now of course the promise
really the resolver reject then what I’m doing is that I am calling done call
back on it now when it runs for the first time when the promise is not there
this is not very interesting but when it calls the lewd song for the second time
this block will not be called the if block will not be true anymore do not go
inside because the promise that the key already exists inside the cache object
and then I need to call dot down on it so what will happen is that the request
will not be called again the request will not be called again instead just
the what is to be done once the requests have been completed
will be called so it’s kind of like this had you as obtain four notes of ten
chapters right and those are ten promises that he made to you you keep
storing the nodes as keeps delivering the promises now if you
want to read the notes right which is the callback here so the callback
function here is what you need to do once the notes are found for a
particular chapter now every time you don’t need to make a call to your friend
that hey I need the notes you can just rely on what has been given to you so
cash is nothing but a storage right so it’s like that you have got the notes
and now you’ve stored them so instead of asking the friend so this is a situation
this block is a situation where you found the nodes of chapter 8 missing so
you called him up and he made a promise to you and you sort of noted it down
somewhere okay chapter 8 notes friend has to give to me now once the promise
is they suppose fulfilled successfully then you can read the notes until then
you cannot read the notes however once that promise has been delivered
successfully you can read the notes multiple times you will get the notes
once but you will read it multiple times that is what the callback is so let’s
suppose a callback here is play the song or load the song whatever right or odd
set it up like show the details of the song so whenever cash I did not done
callback is called it is not that it is going to call for that data again and
again and again it’s just going to call the callback with the original promise
that hey this was a promise this was the data that was fished and this is what
you need to do with it now another thing here is dot main
function and again this directly addresses the callback here that I was
just showing to you as you can see that this is like a call inside a call center
call let’s suppose yet a call you have to load the song in a sequence one two
three you have something called as a differed chaining function where what
you can do is that when the songs have loaded so this is the way you should
read this is more like dollar dot deferred but man
they suppose the dollar doorpost I’m not going to write all the details here
let’s suppose it is a song and it’s for ID one so I can pass n number
such requests and once all of them are served then I’m saying draught then they
suppose songs is what I want to do so I want to load all the three songs and
that’s where that pain will happen help us out in terms of all the requests
being served and of course so they have used it on the Flickr API so they have
created a deferred object they made a request they have caught in the data and
then they resolve the problem is giving back the response data and then you have
the dollar dot pain and this so dot when is being called on TFT so when phase two
eats is done then you get set it up so you’re avoiding the callback Hellyer by
using dot man thank you so much for joining L have a good day all right so
thank you for the great session one I hope all of you found it informative if
you have any further queries related to this session please comment in the
comment section below and we’ll try to reply to you as soon as it’s possible
until then that’s all from our site today thank you
and happy learning. I hope you have enjoyed listening to
this video please be kind enough to like it and you can comment any of your
doubts and queries and we will reply them at the earliest do look out for
more videos in our playlist and subscribe to Edureka channel to learn
more, happy learning.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , ,

12 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *