Professional Documents
Culture Documents
Regular Expression (regex or regexp) is a sequence of characters that define a search pattern. Usually
this pattern is then used by string searching algorithms for "find" or "find and replace" operations on
strings. Each character in a regular expression is understood to be a metacharacter (with its special
meaning), or a regular character (with its literal meaning). To handle regex in python you must import a
modue named re. Syntax is : import re . A regular expression (or RE) specifies a set of strings that
matches it; the functions in this module let you to check if a particular string matches a given regular
expression.
Regular expressions can contain both special and ordinary characters. Most ordinary characters,
like 'A', 'a', or '0', are the simplest regular expressions; they simply match themselves. You can
concatenate ordinary characters, so last matches the string 'last'. Some characters, like '|' or '(', are
special. Special characters either stand for classes of ordinary characters, or affect how the regular
expressions around them are interpreted. Regular expression pattern strings may not contain null bytes,
but can specify the null byte using a \number notation such as '\x00'.
Repetition qualifiers (*, +, ?, {m,n}, etc) cannot be directly nested. This avoids ambiguity with
the non-greedy modifier suffix ?, and with other modifiers in other implementations. To apply a second
repetition to an inner repetition, parentheses may be used. For example, the expression (?:a{6})*
matches any multiple of six 'a' characters.
'^' (Caret.) :Matches the start of the string, and in MULTILINE mode also matches immediately after
each newline.
'$': Matches the end of the string or just before the newline at the end of the string, and in MULTILINE
mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression
foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ‘foo2’
normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in 'foo\n' will find two (empty)
matches: one just before the newline, and one at the end of the string.
'*' : Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as
are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.
'+' : Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’
followed by any non-zero number of ‘b’s; it will not match just ‘a’.
'?' : Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either
‘a’ or ‘ab’.
*?, +?, ?? : The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible.
Sometimes this behaviour isn’t desired; if the RE <.*> is matched against <a> b <c>, it will match the
entire string, and not just <a>. Adding ? after the qualifier makes it perform the match in non-greedy or
minimal fashion; as few characters as possible will be matched. Using the RE <.*?> will match only
<a>.
{m} : Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the
entire RE not to match. For example, a{6} will match exactly six 'a' characters, but not five.
{m,n} : Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to
match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters.
Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an
example, a{4,}b will match aaaab or a thousand 'a' characters followed by a b, but not aaab. The comma
may not be omitted or the modifier would be confused with the previously described form.
{m,n}? : Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to
match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For
example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}? will only
match 3 characters.
'\' : Either escapes special characters (permitting you to match characters like '*', '?', and so forth), or
signals a special sequence; special sequences are discussed below. If you’re not using a raw string to
express the pattern, remember that Python also uses the backslash as an escape sequence in string
literals; if the escape sequence isn’t recognized by Python’s parser, the backslash and subsequent
character are included in the resulting string.
'|' : A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or
B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups
(see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right. When
one pattern completely matches, that branch is accepted. This means that once A matches, B will not be
tested further, even if it would produce a longer overall match. In other words, the '|' operator is never
greedy. To match a literal '|', use \|, or enclose it inside a character class, as in [|].
(...) : Matches whatever regular expression is inside the parentheses, and indicates the start and end
of a group; the contents of a group can be retrieved after a match has been performed, and can be
matched later in the string with the \number special sequence, described below. To match the literals
'(' or ')', use \( or \), or enclose them inside a character class: [(] [)].
(?...) : This is an extension notation (a '?' following a '(' is not meaningful otherwise). The
first character after the '?' determines what the meaning and further syntax of the construct is.
Extensions usually do not create a new group; (?P<name>...) is the only exception to this rule.
Following are the currently supported extensions.
(?aiLmsux) : (One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group
matches the empty string; the letters set the corresponding flags: re.A (ASCII-only matching), re.I
(ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), and re.X
(verbose), for the entire regular expression. This is useful if you wish to include the flags as part of the
regular expression, instead of passing a flag argument to the re.compile() function. Flags should
be used first in the expression string.
(?imsx-imsx:...) : (Zero or more letters from the set 'i', 'm', 's', 'x', optionally followed
by '-' followed by one or more letters from the same set.) The letters set or removes the
corresponding flags: re.I (ignore case), re.M (multi-line), re.S (dot matches all), and re.X
(verbose), for the part of the expression.
(?<=...) : Matches if the current position in the string is preceded by a match for ... that ends at the
current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in abcdef,
since the lookbehind will back up 3 characters and check if the contained pattern matches.
(?<!...) : Matches if the current position in the string is not preceded by a match for This is called a
negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must
only match strings of some fixed length. Patterns which start with negative lookbehind assertions may
match at the beginning of the string being searched.
\number : Matches the contents of the group of the same number. Groups are numbered starting from 1.
For example, (.+) \1 matches 'the the' or '55 55', but not 'thethe' (note the space after the group). This
special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or
number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal
value number. Inside the '[' and ']' of a character class, all numeric escapes are treated as characters.
\b : Matches the empty string, but only at the beginning or end of a word. A word is defined as a
sequence of Unicode alphanumeric or underscore characters, so the end of a word is indicated by
whitespace or a non-alphanumeric, non-underscore Unicode character.
\B : Matches the empty string, but only when it is not at the beginning or end of a word. This means that
r'py\B' matches 'python', 'py3', 'py2', but not 'py', 'py.', or 'py!'. \B is just the opposite of \b, so word
characters are Unicode alphanumerics or the underscore, although this can be changed by using the
ASCII flag.
\d : For Unicode (str) patterns: Matches any Unicode decimal digit (that is, any character in Unicode
character category [Nd]). This includes [0-9], and also many other digit characters. If the ASCII flag is
used only [0-9] is matched (but the flag affects the entire regular expression, so in such cases using an
explicit [0-9] may be a better choice). Matches any decimal digit; this is equivalent to [0-9].
\D : Matches any character which is not a Unicode decimal digit. This is the opposite of \d. If the ASCII
flag is used this becomes the equivalent of [^0-9] (but the flag affects the entire regular expression, so in
such cases using an explicit [^0-9] may be a better choice).
\s : Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other
characters, for example the non-breaking spaces mandated by typography rules in many languages). If
the ASCII flag is used, only [ \t\n\r\f\v] is matched (but the flag affects the entire regular expression, so
in such cases using an explicit [ \t\n\r\f\v] may be a better choice).
\S : Matches any character which is not a Unicode whitespace character. This is the opposite of \s. If the
ASCII flag is used this becomes the equivalent of [^ \t\n\r\f\v] (but the flag affects the entire regular
expression, so in such cases using an explicit [^ \t\n\r\f\v] may be a better choice).
\w : Matches Unicode word characters; this includes most characters that can be part of a word in any
language, as well as numbers and the underscore. If the ASCII flag is used, only [a-zA-Z0-9_] is
matched (but the flag affects the entire regular expression, so in such cases using an explicit [a-zA-Z0-
9_] may be a better choice).
\W : Matches any character which is not a Unicode word character. This is the opposite of \w. If the
ASCII flag is used this becomes the equivalent of [^a-zA-Z0-9_] (but the flag affects the entire regular
expression, so in such cases using an explicit [^a-zA-Z0-9_] may be a better choice).
Compiled regular expression objects support the following methods and attributes:
Scan through string looking for the first location where this regular expression produces a match, and
return a corresponding match object. Return None if no position in the string matches the pattern; note
that this is different from finding a zero-length match at some point in the string.
The optional second parameter pos gives an index in the string where the search is to start; it defaults to
0. This is not completely equivalent to slicing the string; the '^' pattern character matches at the real
beginning of the string and at positions just after a newline, but not necessarily at the index where the
search is to start.
The optional parameter endpos limits how far the string will be searched; it will be as if the string is
endpos characters long, so only the characters from pos to endpos - 1 will be searched for a match.
If zero or more characters at the beginning of string match this regular expression, return a
corresponding match object. Return None if the string does not match the pattern; note that this is
different from a zero-length match.
If the whole string matches this regular expression, return a corresponding match object. Return None if
the string does not match the pattern; note that this is different from a zero-length match.
regex.split(string, maxsplit=0)
Similar to the findall() function, using the compiled pattern, but also accepts optional pos and
endpos parameters that limit the search region like for match().
Similar to the finditer() function, using the compiled pattern, but also accepts optional pos and
endpos parameters that limit the search region like for match().
regex.flags
The regex matching flags. This is a combination of the flags given to compile(), any (?...) inline
flags in the pattern, and implicit flags such as UNICODE if the pattern is a Unicode string.
regex.groups
regex.groupindex
A dictionary mapping any symbolic group names defined by (?P<id>) to group numbers. The
dictionary is empty if no symbolic groups were used in the pattern.
regex.pattern
Method/Attribute Purpose
match() Determine if the RE matches at the beginning of the string.
search() Scan through a string, looking for any location where this RE matches.
MySQL - Introduction
What is a Database?
A database is a separate application that stores a collection of data. Each database has one or more
distinct APIs for creating, accessing, managing, searching and replicating the data it holds. A database
is an organized collection of data It is a collection of schemas, tables, queries, reports, views, and other
objects. Database designers typically organize the data to model aspects of reality in a way that supports
processes requiring information, such as (for example) modelling the availability of rooms in hotels in a
way that supports finding a hotel with vacancies.
Other kinds of data stores can also be used, such as files on the file system or large hash tables in
memory but data fetching and writing would not be so fast and easy with those type of systems.
RDBMS Terminology
Table − A table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column − One column (data element) contains data of one and the same kind, for example the
column postcode.
Row − A row (= tuple, entry or record) is a group of related data, for example the data of one
subscription.
Redundancy − Storing data twice, redundantly to make the system faster.
Primary Key − A primary key is unique. A key value can not occur twice in one table. With a
key, you can only find one row.
Foreign Key − A foreign key is the linking pin between two tables.
Compound Key − A compound key (composite key) is a key that consists of multiple columns,
because one column is not sufficiently unique.
Index − An index in a database resembles an index at the back of a book.
Referential Integrity − Referential Integrity makes sure that a foreign key value always points
to an existing row.
MySQL
MySQL is the most popular Open Source Relational SQL Database Management System. It is the best
RDBMS being used for developing various web-based software applications. MySQL is developed,
marketed and supported by MySQL AB, which is a Swedish company. MySQL is a fast, easy-to-use
RDBMS being used for many small and big businesses. MySQL is developed, marketed and supported
by MySQL AB, which is a Swedish company. MySQL is becoming so popular because of many good
reasons −
MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL is a very powerful program in its own right. It handles a large subset of the functionality
of the most expensive and powerful database packages.
MySQL works on many operating systems and with many languages including PHP, PERL, C,
C++, JAVA, etc.
MySQL works very quickly and works well even with large data sets.
MySQL is very friendly to PHP, the most appreciated language for web development.
MySQL supports large databases, up to 50 million rows or more in a table. The default file size
limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments.
SELECT Statement
DISTINCT Clause
WHERE Clause
AND/OR Clause
IN Clause
BETWEEN Clause
LIKE Clause
GROUP BY Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
COUNT Clause
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
HAVING Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
Update Query :
UPDATE command will modify any field value of any MySQL table.
You can update one or more field altogether.
You can specify any condition using the WHERE clause.
You can update the values in a single table at a time.
The WHERE clause is very useful when you want to update the selected rows in a table.
ALTER command is very useful when you want to change a name of your table, any table field or if you
want to add or delete an existing column in a table.
INSERT Query
To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can
insert data into the MySQL table by using this command.
(value1, value2,...valueN );
DELETE Query
If you want to delete a record from any MySQL table, then you can use the SQL command DELETE
FROM. The WHERE clause is very useful when you want to delete selected rows in a table. If the
WHERE clause is not specified, then all the records will be deleted from the given MySQL table.
The public interface is provided through a number of Python modules. The most important interface
module is the Tkinter module itself. To use Tkinter, all you need to do is to import the Tkinter module:
import Tkinter
The Tkinter module only exports widget classes and associated constants, so you can safely use the
from-in form in most cases. If you prefer not to, but still want to save some typing, you can use import-
as:
import Tkinter as Tk
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and
easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk
GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following
steps −
Import the Tkinter module.
Enter the main event loop to take action against each event triggered by the user.
Hyper Text Markup Language (HTML
HTML is the standard markup language for creating Web pages.
HTML stands for Hyper Text Markup Language
HTML describes the structure of Web pages using markup
HTML elements are the building blocks of HTML pages
HTML elements are represented by tags
HTML tags label pieces of content such as "heading", "paragraph", "table", and so on
Browsers do not display the HTML tags, but use them to render the content of the page
HTML elements can be divided into two categories : block level and inline elements.
1. HTML block level elements can appear in the body of an HTML page.
2. It can contain other block level as well as inline elements.
3. By default, block-level elements begin on new lines.
4. block level elements create larger structures (than inline elements).
List of block level elements
p
h1, h2, h3, h4, h5, h6
ol, ul, dl
div
fieldset
form
hr
table
Inline Elements
HTML inline level elements can appear in the body of an HTML page.
HTML5 DOCTYPE.
DOCTYPE is the first thing which should be present in an HTML5 document.
'DOCTYPE' keyword is not case sensitive. So, <!doctype html> or <!DOCTYPE html>, both
will do.
HTML5 doctype does not reference to a DTD. This is because, html5 is a SGML based, unlike
HTML4.01 or XHTML1.
As soon a browser finds <!doctype html> in the starting of an HTML document, it represents the
document in standard mode. If you don't use doctype in the starting of an HTML document, browser
goes to the quirky mode. In that case, you may find that certain content is not being displayed the
way you marked them up. So, it is a good practice to start your HTML document with a doctype.
Even if you don't use any other new HTML5 tag or feature, since the browser goes to the standard
mode, you can use the doctype of html5.
1. Writing CSS code in a separate file (CSS files are saved with .css extension) and
including that CSS file in head section of an HTML page using <link> element.
2. Writing CSS code as a value of style attribute of an HTML element whose presentation
you like to set. This is called as inline style.
3.Writing CSS code within style tags, within the head section of the HTML page
Writing CSS code in another CSS file and attaching it to an HTML page, you can separate
content from presentation. So, as an author, you need not to be concerned about presentation and
concentrate on content only.
2. Consistency :
CSS can provide a consistent presentation for all of the pages of a website.
3.Increment in accessibility :
If a particular page (or a number of pages ) needs a different look and formatting, with a change
of a single line, that can be achieved by calling more than one CSS for the same page.
4. Save of bandwidth :
Since CSS separates content form style, it makes a web document lightweight, causing saving of
bandwidth and in turn faster loading of page.
5. Ease of contribution :
Content Management Systems (for example WordPress) uses CSS, so that people without
bothering how their content will look, can submit their content.This has caused exponential increase in
User Generated Content.
1. CSS comments stop the CSS style rules written within a CSS stylesheet, from being processed while
displaying an HTML document in browser.
2. CSS comments start with "/*" and end with "*/". You can use this both
4. CSS comment can not be nested, i.e. a comment can not hold another comment within it.
5. You can use HTML style comment ( "<!--................ -->" ) in a CSS stylesheet also. But it does not
have anything to do with CSS comments.
xy
Descendant selectors
x>y
Child selectors
x+y
Adjacent sibling selectors
.classname
Class selectors
#idname
ID selectors
:first-line | :first-letter | :before and :after
Pseudo-elements
:first-child | :link and :visited | :hover, :active, and :focus | :lang
Pseudo-classes
BootStrap
What is Bootstrap?
Responsive Web Design (RWD) is a best way to optimize website viewing in different kind of devices
such as desktop, tablet, mobile etc. This kind of website get more traffic compare to other websites.
Responsive website dynamically reduce website size and increase website loading speed for various
devices. Bootstrap is a sleek, intuitive, and powerful mobile first front-end framework for faster and
easier web development. It uses HTML, CSS and Javascript. Bootstrap was developed by Mark Otto
and Jacob Thornton at Twitter. It was released as an open source product in August 2011 on GitHub.
Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper
alignment and padding.
Use rows to create horizontal groups of columns.
Content should be placed within columns, and only columns may be immediate children of rows.
Predefined grid classes like .row and .col-xs-4 are available for quickly making grid layouts.
Less mixins can also be used for more semantic layouts.
Columns create gutters (gaps between column content) via padding. That padding is offset in
rows for the first and last column via negative margin on .rows.
The negative margin is why the examples below are outdented. It's so that content within grid
columns is lined up with non-grid content.
Grid columns are created by specifying the number of twelve available columns you wish to
span. For example, three equal columns would use three .col-xs-4.
If more than 12 columns are placed within a single row, each group of extra columns will, as one
unit, wrap onto a new line.
Grid classes apply to devices with screen widths greater than or equal to the breakpoint sizes,
and override grid classes targeted at smaller devices. Therefore, e.g. applying any .col-md-*
class to an element will not only affect its styling on medium devices but also on large devices if
a .col-lg-* class is not present.
JAVASCRIPT
What is a script?
A script is an executable list of commands like macro or batch file created by a scripting language.
Scripts (like PHP, Perl) which are executed on a web server are called server-side scripts and scripts
(like JavaScript) which are executed on user's computer, interpreted by the browser is called client-side
scripts.
What is javascript?
1. Case sensitivity
JavaScript is case sensitive. Therefore when we write any JavaScript word (for example "else") we must
maintain proper case. As JavaScript is case sensitive , a variable name "empcode" is not the same as
"Empcode" or a function name "PayCalculation" is not the same as "paycalculation".
Always remember everything within <script type="text/javascript">and <script> tags (which are HTML
tags) are case sensitive.
2. Whitespace
In general, whitespace is not visible on the screen, including spaces, tabs and newline characters.
Whitespace enhances readability of the JavaScript code. If used within string constant, JavaScript
considers it, but if not so, it ignores whitespace.
3. The Semi-Colon
In general JavaScript does not require a semi-colon at the end of a statement. If you write two
statements in a single line then a semi-colon is required at the end of the first statement. However
experienced programmers prefer to use a semi-colon at the end of each statement to make the code more
readable and fix errors easily.
4. Comments
Code written within comments are not processed by the interpreter. Comments are good way to write
notations to explain what a script does. JavaScript supports the following two different ways of
commenting, single line comment and multiple line comments.
Single line comment
// This is a single line comment.
Multiple line comments
In JavaScript multi line comments start with /* and end with */.
Javascript function to check if a field input contains letters and numbers only
// Function to check letters and numbers
function alphanumeric(inputtxt)
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if((inputtxt.value.match(letterNumber))
{s
return true;
}
else
{
alert("message");
return false;
}
}
What is JSON
JSON syntax is basically considered as a subset of JavaScript syntax; it includes the following −
Data is represented in name/value pairs.
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are
separated by , (comma).
Square brackets hold arrays and values are separated by ,(comma).
Before you start with encoding and decoding JSON using Python, you need to install any of the JSON
modules available. Also we can import json module to out program using import statement ;
import json
JSON Functions
Function Libraries
encode Encodes the Python object into a JSON string representation.
decode Decodes a JSON-encoded string into a Python object.
The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of
common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods
that you can call with a single line of code. jQuery also simplifies a lot of the complicated things from
JavaScript, like AJAX calls and DOM manipulation.
HTML/DOM manipulation
CSS manipulation
Utilities
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the
element(s).
Examples:
You might have noticed that all jQuery methods in our examples, are inside a document ready event:
$(document).ready(function()
{
//jQuerymethods
});
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to
"find" (or select) HTML elements based on their id, classes, types, attributes, values of attributes and
much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $(). A jQuery Selector is a function
which makes use of expressions to find out matching elements from a DOM based on the given criteria.
Simply you can say, selectors are used to select one or more HTML elements using jQuery. Once an
element is selected then we can perform various operations on that selected element.
i) The element Selector
The jQuery element selector selects elements based on the element name.You can select all <p>
elements on a page like this.
$("p")
Example:
$(document).ready(function()
$("button").click(function(){
$("p").hide();
});
});
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should
be unique within a page, so you should use the #id selector when you want to find a single, unique
element.
To find an element with a specific id, write a hash character, followed by the id of the element:$("#test")
Example:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
iii) The .class Selector
The jQuery class selector finds elements with a specific class. To find elements with a specific class,
write a period character, followed by the name of the class: $(".test")
jQuery Methods
Method Description
bind() Attaches event handlers to elements
blur() Attaches/Triggers the blur event
change() Attaches/Triggers the change event
click() Attaches/Triggers the click event
dblclick() Attaches/Triggers the double click event
Attaches a handler to current, or future, specified child
delegate()
elements of the matching elements
The current DOM element within the event bubbling
event.currentTarget
phase
Contains the optional data passed to an event method
event.data
when the current executing handler is bound
Returns the element where the currently-called jQuery
event.delegateTarget
event handler was attached
Returns whether event.preventDefault() was called for the
event.isDefaultPrevented()
event object
Returns whether event.stopImmediatePropagation() was
event.isImmediatePropagationStopped()
called for the event object
Returns whether event.stopPropagation() was called for
event.isPropagationStopped()
the event object
Returns the namespace specified when the event was
event.namespace
triggered
Returns the mouse position relative to the left edge of the
event.pageX
document
Returns the mouse position relative to the top edge of the
event.pageY
document
event.preventDefault() Prevents the default action of the event
Returns which element being entered or exited on mouse
event.relatedTarget
movement.
Contains the last/previous value returned by an event
event.result
handler triggered by the specified event
event.stopImmediatePropagation() Prevents other event handlers from being called
Prevents the event from bubbling up the DOM tree,
event.stopPropagation() preventing any parent handlers from being notified of the
event
event.target Returns which DOM element triggered the event
Returns the number of milliseconds since January 1, 1970,
event.timeStamp
when the event is triggered
event.type Returns which event type was triggered
Returns which keyboard key or mouse button was pressed
event.which
for the event
focus() Attaches/Triggers the focus event
focusin() Attaches an event handler to the focusin event
focusout() Attaches an event handler to the focusout event
hover() Attaches two event handlers to the hover event
keydown() Attaches/Triggers the keydown event
keypress() Attaches/Triggers the keypress event
keyup() Attaches/Triggers the keyup event
mousedown() Attaches/Triggers the mousedown event
mouseenter() Attaches/Triggers the mouseenter event
mouseleave() Attaches/Triggers the mouseleave event
mousemove() Attaches/Triggers the mousemove event
mouseout() Attaches/Triggers the mouseout event
mouseover() Attaches/Triggers the mouseover event
mouseup() Attaches/Triggers the mouseup event
off() Removes event handlers attached with the on() method
on() Attaches event handlers to elements
Adds one or more event handlers to selected elements.
one()
This handler can only be triggered once per element
$.proxy() Takes an existing function and returns a new one with a
particular context
Specifies a function to execute when the DOM is fully
ready()
loaded
resize() Attaches/Triggers the resize event
scroll() Attaches/Triggers the scroll event
select() Attaches/Triggers the select event
submit() Attaches/Triggers the submit event
Removed in version 1.9. Attaches two or more functions
toggle()
to toggle between for the click event
trigger() Triggers all events bound to the selected elements
Triggers all functions bound to a specified event for the
triggerHandler()
selected elements
unbind() Removes an added event handler from selected elements
Removes an event handler to selected elements, now or in
undelegate()
the future
With jQuery you can fade an element in and out of visibility. jQuery has the following fade methods:
fadeIn()
fadeOut()
fadeToggle()
fadeTo()
1. fadeIn()
Syntax:
$(selector).fadeIn(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds. The optional callback parameter is a function to be executed after the
fading completes.
2. fadeOut()
Syntax:
$(selector).fadeOut(speed,callback);
3. fadeToggle()
The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods. If the elements
are faded out, fadeToggle() will fade them in. If the elements are faded in, fadeToggle() will fade them
out.
Syntax:
$(selector).fadeToggle(speed,callback);
4. fadeTo()
The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).
Syntax:
$(selector).fadeTo(speed,opacity,callback);
With jQuery you can create a sliding effect on elements. jQuery has the following slide methods:
slideDown()
slideUp()
slideToggle()
1. slideDown()
Syntax:
$(selector).slideDown(speed,callback);
2. slideUp()
Syntax:
$(selector).slideUp(speed,callback);
Example:
$(document).ready(function()
$("#flip").click(function(){
$("#panel").slideUp("slow");
});
});
3. slideToggle()
The jQuery slideToggle() method toggles between the slideDown() and slideUp() methods. If the
elements have been slid down, slideToggle() will slide them up.If the elements have been slid up,
slideToggle() will slide them down.
Syntax:
$(selector).slideToggle(speed,callback);
Example:
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
jQuery Animate method
Syntax:
$(selector).animate({params},speed,callback);
Example:
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left:'250px'});
});
});
Example:
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left:'250px',
opacity:'0.5',
height:'150px',
width:'150px'
});
});
});
jQuery animate() - Using Relative Values
It is also possible to define relative values (the value is then relative to the element's current value). This
is done by putting += or -= in front of the value:
Example:
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left:'250px',
height:'+=150px',
width:'+=150px'
});
});
});
You can even specify a property's animation value as "show", "hide", or "toggle": Example:$
(document).ready(function(){
$("button").click(function(){
$("div").animate({
height:'toggle'
});
});
});
jQuery animate() - Uses Queue Functionality
By default, jQuery comes with queue functionality for animations. This means that if you write
multiple animate() calls after each other, jQuery creates an "internal" queue with these method calls.
Then it runs the animate calls ONE by ONE.
Example:
$(document).ready(function(){
$("button").click(function(){ var div=$("div");
div.animate({height:'300px',opacity:'0.4'},"slow");
div.animate({width:'300px',opacity:'0.8'},"slow");
div.animate({height:'100px',opacity:'0.4'},"slow");
div.animate({width:'100px',opacity:'0.8'},"slow");
});
});
The jQuery stop() method is used to stop an animation or effect before it is finished. The stop() method
works for all jQuery effect functions, including sliding, fading and custom animations.
Syntax:
$(selector).stop(stopAll,goToEnd);
Example:
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});
jQuery Callback Functions
Syntax:
$(selector).hide(speed,callback);
Example:
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow",function()
hidden");
});
});
});
Until now we have been writing jQuery statements one at a time (one after the other). However, there is
a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the
same element(s).
Example:
$(document).ready(function()
$("button").click(function(){
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
});
});
jQuery - Get Content and Attributes
Three simple, but useful, jQuery methods for DOM manipulation are:
text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
The following example demonstrates how to get content with the jQuery text() and html() methods:
Example:
$(document).ready(function(){
$("#btn1").click(function()
});
$("#btn2").click(function()
{ alert("HTML: " + $
("#test").html());
});
});
Example:
$(document).ready(function(){
$("button").click(function(){
alert($("#w3s").attr("href"));
});
});
jQuery - Set Content and Attributes
We will use the same three methods from the get content to set content:
Example:
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
});
The callback function has two parameters: the index of the current element in the list of elements
selected and the original (old) value. You then return the string you wish to use as the new value from
the function.
Example:
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text(function(i,origText){
return "Old text: " + origText + " New text: Hello world! (index: " + i + ")";
});
});
$("#btn2").click(function(){
$("#test2").html(function(i,origText){
return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")";
});
});
});
The jQuery attr() method is also used to set/change attribute values.This method also allows you to set
multiple attributes at the same time.
Example:
$(document).ready(function(){
$("button").click(function(){
$("#w3s").attr("href","http://www.w3schools.com/jquery");
});
});
The jQuery method attr(), also come with a callback function. The callback function has two
parameters: the index of the current element in the list of elements selected and the original (old)
attribute value. Return the string you wish to use as the new attribute value from the function.
Example:
$(document).ready(function(){
$("button").click(function(){
$("#w3s").attr("href", function(i,origValue){
});
});
});
jQuery - Add Elements
There are mainly two jQuery methods to remove elements and content
Example:
$(document).ready(function(){
$("button").click(function(){
$("h1,h2,p").addClass("blue");
$("div").addClass("important");
});
});
jQuery removeClass() Method
Example:
$(document).ready(function(){
$("button").click(function(){
$("h1,h2,p").removeClass("blue");
});
});
The jQuery toggleClass() method toggles between adding/removing classes from the selected elements:
Example:
$(document).ready(function(){
$("button").click(function(){
$("h1,h2,p").toggleClass("blue");
});
});
jQuery Traversing
jQuery traversing, which means "move through", are used to "find" (or select) HTML elements based on
their relation to other elements. Start with one selection and move through that selection until you reach
the elements you desire. With jQuery traversing, you can easily move up (ancestors), down
(descendants) and sideways (siblings) in the family tree, starting from the selected (current) element.
This movement is called traversing - or moving through - the DOM.
jQuery Traversing Methods
Method Description
add() Adds elements to the set of matched elements
addBack() Adds the previous set of elements to the current set
children() Returns all direct children of the selected element
closest() Returns the first ancestor of the selected element
Returns all direct children of the selected element (including text and comment
contents()
nodes)
each() Executes a function for each matched element
Ends the most recent filtering operation in the current chain, and return the set of
end()
matched elements to its previous state
eq() Returns an element with a specific index number of the selected elements
Reduce the set of matched elements to those that match the selector or pass the
filter()
function’s test
find() Returns descendant elements of the selected element
first() Returns the first element of the selected elements
has() Returns all elements that have one or more elements inside of them
Checks the set of matched elements against a selector/element/jQuery object, and
is()
return true if at least one of these elements matches the given arguments
last() Returns the last element of the selected elements
Passes each element in the matched set through a function, producing a new jQuery
map()
object containing the return values
next() Returns the next sibling element of the selected element
nextAll() Returns all next sibling elements of the selected element
nextUntil() Returns all next sibling elements between two given arguments
not() Remove elements from the set of matched elements
offsetParent() Returns the first positioned parent element
parent() Returns the direct parent element of the selected element
parents() Returns all ancestor elements of the selected element
parentsUntil() Returns all ancestor elements between two given arguments
prev() Returns the previous sibling element of the selected element
prevAll() Returns all previous sibling elements of the selected element
prevUntil() Returns all previous sibling elements between two given arguments
siblings() Returns all sibling elements of the selected element
slice() Reduces the set of matched elements to a subset specified by a range of indices
What are Events?
All the different visitor's actions that a web page can respond to are called events. An event represents
the precise moment when something happens.
blur()
The blur() method attaches an event handler function to an HTML form field.
The function is executed when the form field loses focus:
AngularJS
AngularJS is a very powerful Framework. It is used in Single Page Application (SPA) projects. It
extends HTML DOM with additional attributes and makes it more responsive to user actions.
AngularJS version 1.0 was released in 2012. Miško Hevery, a Google employee, started to work with
AngularJS in 2009. AngularJS is a JavaScript framework. It can be added to an HTML page with a
<script> tag.
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
FEATURES OF AngularJS
1. The MVC Framework : AngularJs is an MVC based framework, where the Model for a
controller contains data, the controller for a view contains the logic to manipulate that data, and the
view is the HTML that displays the data. A $scope can be considered as a model, whereas the functions
written in angular controller modifies the $scope and HTML display the value of the scope variable
2. HTML User Interface : The main fact about AngularJS is that it uses the HTML language to build
user interfaces. The HTML language is a common and declarative language with very short tags that are
simple to understand. This leads to a more organised and simplistic UI. JavaScript interfaces are often
more complicated to develop and organise.
3. Behaviour with Directives : Angular provides extra functionality with the HTML language
using directives. The additional elements in the system can be accessed with no need for the DOM to
simulate additional elements. The controller doesn't need to manipulate the DOM directly, as this should
be done through directives. Directives make up a separate part of the element set which can be used
anywhere other than in a web application. Directives give developers the element-rich HTML they need
to strengthen their online presence.
5. Filtering : AngularJS framework simply filters out the data before it reaches the view. They perform
paginations, as well as filtering data arrays with respect to available parameters. The functions can be
modified according to the ideal parameters in your system, but these are the only data transformation
tasks done. The system works by putting information into the right format before it's delivered to the end-
user.
6. Unit Testing Facilities : Reliability and performance are an important part of making sure that a
site works as it should. Before AngularJS, testing would have to be performed by creating an individual
test page and using that page to test the behaviour of each component. This was a frustrating and time-
consuming process. But with AngularJS, the testing process can become a lot simpler. The application
simply uses Dependency injection to bind the application together. This helps everything to function as it
should while managing the control with a lot of simplicity. All the controllers available within the
AngularJS unit testing facilities are dependent on the dependency injection, which means that you can
adjust certain aspects to find out the preferred configuration for data or an app.
7. Templates : In AngularJS, it's possible to use templates to help you build the perfect framework
faster. In this network, your template is made of plain HTML, but the language can be extended to
include instructions on how the model should be shown in the end view. Templates can be parsed by the
browser into the DOM, which then becomes the input for the AngularJS compiler.
The unique templates offered by AngularJS makes it easier for designers and developers to work together.
Designers can mark up HTML normally, while developers take on the functionality aspects with little
effort.
AngularJS Expressions
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
OR
<div ng-app="" ng-init="myCol='lightblue'">
<input style="background-color:{{myCol}}" ng-model="myCol">
</div>
AngularJS Modules
An AngularJS module defines an application. Module is a container for the different parts of an
application. The module is a container for the application controllers. Controllers always belong to a
module. There can't be more than one ng-apps for a single AngularJS application. The ng-app
directive conveys AngularJS application that it is the root element. In your HTML document,
you can have a single ng-app directive only. In case of more than one ng-app directives, the
first appearance will be used.
AngularJS Scope
The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an
object with the available properties and methods. The scope is available for both the view and the
controller.
<h1>{{carname}}</h1>
</div>
<script>
app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});
</script>
AngularJS Filters
Filters can be added in AngularJS to format data. Filters can be added to expressions by using the pipe
character |, followed by a filter.