Elements of Commercial Portals
Elements of Commercial Portals
Unit I - HTML 5
HTML5 is the latest version of the Hypertext Markup Language used for structuring and presenting content
on the World Wide Web. It introduces a wide range of new features, including semantic elements,
multimedia support, form enhancements, and more. Here's an overview of HTML5 and some of its key
form elements and attributes:
Introduction to HTML5
HTML5 is the fifth version of HTML, the language used to create and design web pages. It includes new
elements, attributes, and APIs (Application Programming Interfaces) that offer improved semantics,
multimedia support, and better accessibility. HTML5 is backward compatible with older HTML versions,
making it easy for developers to transition to the new standard.
Attributes in HTML5
HTML5 also introduced new attributes to enhance form controls and improve accessibility. Some of the
key attributes include:
• Placeholder Attribute: Specifies a short hint that describes the expected value of an input field.
• Autofocus Attribute: Specifies that an input field should automatically get focus when the page
loads.
• Required Attribute: Specifies that an input field must be filled out before submitting the form.
Attributes:
➢ Placeholder Attribute
Provides a short hint that describes the expected value of an input field.
<input type="text" name="username" placeholder="Enter your username">
➢ Autofocus Attribute
Specifies that an input field should automatically get focus when the page loads.
<input type="text" name="search" autofocus>
➢ Required Attribute
Specifies that an input field must be filled out before submitting the form.
<input type="text" name="fullname" required>
Unit II - XML
XML, or Extensible Markup Language, is a markup language that defines a set of rules for encoding
documents in a format that is both human-readable and machine-readable. It is a versatile and widely-used
standard for representing structured data, designed to be self-descriptive and easily extensible.
At its core, XML consists of a set of rules for defining custom markup languages and structuring data
hierarchically using tags enclosed in angle brackets. These tags are used to identify and organize different
types of information within the document. Additionally, XML allows for the use of attributes within tags to
provide additional metadata or properties.
XML documents are plain text files that adhere to these rules, making them platform-independent and easily
exchangeable between different systems and applications. They are commonly used for storing and
transmitting structured data across networks, as well as for configuration files, data interchange formats,
and more.
Key features of XML include:
1. Extensibility: XML is extensible, meaning that users can define their own tags and structure to
represent their data. This allows for the creation of custom markup languages tailored to specific
needs.
2. Self-Descriptiveness: XML documents are self-descriptive, as they contain both data and metadata
about the structure and meaning of the data. This metadata is provided through the use of tags,
attributes, and element hierarchy.
3. Hierarchical Structure: XML documents have a hierarchical structure consisting of nested
elements. This hierarchical structure allows for the representation of complex relationships between
different pieces of data.
4. Platform and Language Independence: XML is platform-independent and language-independent,
meaning that XML documents can be created, processed, and interpreted on any platform and by
any programming language that supports XML parsing.
5. Human Readable: XML documents are designed to be easily readable and understandable by
humans. The use of plain text format and descriptive tags makes it easy to interpret the content of
an XML document.
6. Interoperability: XML facilitates interoperability between different systems by providing a
common format for data exchange. This enables seamless communication between heterogeneous
systems, regardless of the underlying technologies.
7. Validation: XML documents can be validated against a specific schema to ensure that they conform
to a predefined structure and content rules. This helps in maintaining data integrity and consistency
across different applications.
8. Transformation: XML documents can be transformed into other formats using technologies such
as XSLT (Extensible Stylesheet Language Transformations). This allows for the conversion of XML
data into various output formats like HTML, PDF, or plain text.
BCA III Year VI Semester – Elements of Commercial Portals
In this example, the style attribute is used to apply CSS styles directly to the <title> elements. The styles
include making the text bold and changing the color to blue for the first book, and green for the second
book.
Alternatively, you can also reference an external CSS file in your XML document, similar to how it's
done in HTML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="styles.css"?>
<!DOCTYPE library SYSTEM "library.dtd">
<library>
<!-- Book elements here -->
</library>
BCA III Year VI Semester – Elements of Commercial Portals
In this case, the <?xml-stylesheet?> processing instruction is used to link an external CSS file named
styles.css to the XML document. The styles defined in the CSS file will then be applied to the elements in
the XML document according to the selectors specified in the CSS.
DSO typically stands for "Data Source Object." It's a technology often associated with Microsoft
technologies, particularly with regards to database connectivity. XML can be used in conjunction with DSO
for various purposes, such as representing data structures or configurations. Below is an example of XML
with DSO:
<?xml version="1.0"?>
<library>
<book>
<title>A Game of Thrones</title>
<author>George RR Martin</author>
<genre>Fantasy</genre>
<price>19.99</price>
</book>
<book>
<title>The Fellowship of the Ring</title>
<author>J.R.R. Tolkien</author>
<genre>Fantasy</genre>
<price>24.99</price>
</book>
</library>
In this XML example, we have a simple representation of a library with two books. Each <book> element
contains child elements such as <title>, <author>, <genre>, and <price> representing different attributes
of the book.
DSO can be utilized to connect and manipulate data from this XML structure within Microsoft technologies,
such as integrating it with databases or other data sources. For instance, you might use DSO to query this
XML structure, extract information, or perform operations based on the data represented in XML. However,
the specific implementation and usage of DSO would depend on the context and technologies involved.
XML Namespacing
XML Namespacing allows elements and attributes in an XML document to be uniquely identified, even
when they have the same name, by associating them with a namespace. Namespaces are commonly used to
avoid naming conflicts between elements and attributes in XML documents, especially when integrating
multiple XML vocabularies or when defining custom XML vocabularies.
XML Namespacing helps in organizing and managing XML documents, especially in scenarios where
multiple XML vocabularies are combined or when elements and attributes need to be uniquely identified
to avoid conflicts. It promotes interoperability by providing a standardized way to integrate XML
vocabularies and data from different sources.
XML DTD
A Document Type Definition (DTD) is a formal declaration of the structure and constraints of an XML
document. It defines the rules and grammar that specify what elements and attributes are allowed in the
document, as well as their hierarchical relationships and data types. DTDs are used to validate XML
documents against a predefined set of rules to ensure their conformance to a specific structure.
DTDs provide a way to formally define the structure and constraints of XML documents, facilitating
validation and ensuring consistency in data representation. However, it's worth noting that DTDs have
limitations and are gradually being replaced by other schema languages like XML Schema Definition
(XSD) and Relax NG, which offer more features and capabilities for XML validation.
<xs:element name="library">
<xs:complexType>
<xs:sequence>
<xs:element name="book" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="genre" type="xs:string"/>
<xs:element name="publisher">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="year" type="xs:gYear"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
<xs:attribute name="ISBN" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
BCA III Year VI Semester – Elements of Commercial Portals
In this XSD schema:
• The <xs:schema> element declares the XML namespace for XSD.
• The <xs:element> elements define the structure of XML elements.
• The <xs:complexType> elements define the content model of complex elements.
• The <xs:sequence> elements define the sequence of child elements within complex elements.
• The <xs:element> elements within <xs:sequence> specify the child elements of complex elements.
• The <xs:attribute> elements define attributes of elements.
This XSD schema describes a library containing books. Each book has a title, author, genre, publisher
(consisting of name and year), and price. The ISBN attribute of the book element is required.
write a simple XSLT stylesheet to transform an XML document into an HTML table:
<xsl:template match="/">
<html>
<head>
<title>Library Catalog</title>
</head>
<body>
<h1>Library Catalog</h1>
<table border="1">
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Publisher</th>
<th>Year</th>
<th>Price</th>
</tr>
<xsl:apply-templates select="library/book"/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="genre"/></td>
<td><xsl:value-of select="publisher/name"/></td>
<td><xsl:value-of select="publisher/year"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
BCA III Year VI Semester – Elements of Commercial Portals
This XSLT stylesheet transforms an XML document conforming to the library schema into an HTML table,
displaying information about each book. The <xsl:template> elements define rules for matching XML
elements and generating HTML output. The <xsl:apply-templates> element is used to apply templates to
selected XML nodes, and <xsl:value-of> is used to output the value of selected XML nodes.
When applied to an XML document containing library data, this XSLT stylesheet will produce an HTML
table displaying the catalog of books.
SAX Parser:
SAX parsing is an event-driven parsing approach where the parser reads the XML document sequentially
and generates events as it encounters different parts of the document. These events (such as start element,
end element, characters, etc.) trigger callback methods in a handler class provided by the application.
DOM Parser:
DOM parsing builds an in-memory tree structure representing the entire XML document, which allows
random access to different parts of the document. This tree structure can then be traversed and manipulated
using the DOM API.
Advantages of DOM Parser:
1. Random access: DOM parsing provides random access to any part of the XML document since it
builds an in-memory tree structure.
2. Easy manipulation: Once parsed, the XML document can be easily manipulated, updated, or
modified using the DOM API.
3. Better suited for smaller documents: DOM parsing is well-suited for smaller XML documents as it
requires loading the entire document into memory.
if your application needs to process large XML documents efficiently with a low memory footprint,
consider using SAX parsing. On the other hand, if random access to different parts of the XML document
and easy manipulation are required, DOM parsing may be more suitable, especially for smaller XML
documents.
BCA III Year VI Semester – Elements of Commercial Portals
SOAP (Simple Object Access Protocol)
SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information in the
implementation of web services. It is a messaging protocol that allows programs running on different
operating systems, platforms, or programming languages to communicate with each other over the internet.
Key components and concepts of SOAP include:
1. XML-based Messaging: SOAP messages are typically encoded in XML format, making them
human-readable and easily understandable. This XML format enables interoperability between
different systems, as XML is platform-independent and widely supported.
2. Message Structure: SOAP messages consist of an envelope, header, body, and optional fault
element. The envelope element encapsulates the entire message, while the header contains optional
metadata and the body contains the actual data being transmitted.
3. Transport Independence: SOAP messages can be transported over various protocols such as
HTTP, SMTP, or TCP. HTTP is commonly used for transporting SOAP messages over the internet,
making SOAP-based web services accessible via standard web protocols.
4. Remote Procedure Calls (RPC): SOAP supports RPC-style communication, allowing clients to
invoke methods or functions exposed by a web service, passing parameters and receiving results in
return.
5. WSDL (Web Services Description Language): WSDL is an XML-based language used to describe
the interface and functionality of web services. It defines the operations supported by the service,
the message format for each operation, and the location of the service endpoint.
6. Interoperability: SOAP is designed to facilitate interoperability between different systems,
platforms, and programming languages. By using standard protocols and XML-based messaging,
SOAP enables communication between heterogeneous systems regardless of their underlying
technologies.
7. Security: SOAP supports various security mechanisms such as SSL/TLS for transport-level security
and WS-Security for message-level security. These mechanisms help ensure the confidentiality,
integrity, and authenticity of SOAP messages exchanged between clients and servers.
Overall, SOAP provides a standardized and extensible framework for building distributed systems and web
services, enabling seamless communication and interoperability between disparate systems across the
internet. Despite the rise of alternative web service protocols like REST, SOAP remains widely used in
enterprise environments where features such as formal contract definition, strong typing, and security are
critical requirements.
SOAP Request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:weat="http://example.com/weather">
<soapenv:Header/>
<soapenv:Body>
<weat:GetWeatherRequest>
<weat:City>New York</weat:City>
</weat:GetWeatherRequest>
</soapenv:Body>
</soapenv:Envelope>
BCA III Year VI Semester – Elements of Commercial Portals
In this example:
• <soapenv:Envelope>: The outermost element represents the SOAP envelope, encapsulating the
entire SOAP message. It declares namespaces for SOAP envelope (soapenv) and for the weather
service (weat).
• <soapenv:Header>: The optional SOAP header may contain additional metadata or authentication
information, but in this example, it's omitted.
• <soapenv:Body>: The SOAP body contains the actual payload of the message. It contains the
request to the weather service.
• <weat:GetWeatherRequest>: This element represents the specific request being made to the
weather service, in this case, a request to get weather information.
• <weat:City>: This element contains the name of the city for which the weather information is
requested (in this case, "New York").
Upon receiving this request, the weather service would process it and generate a SOAP response, typically
structured similarly to the request, but containing the requested weather information.
These XML snippets illustrate the basic structure of SOAP messages, including the SOAP envelope, header,
body, and the payload specific to the web service operation being invoked.
BCA III Year VI Semester – Elements of Commercial Portals
Syntax Overview:
1. Selecting Elements: jQuery uses CSS-style selectors to select elements from the DOM. For
example:
• Select by element name: $('p')
• Select by class name: $('.myClass')
• Select by ID: $('#myId')
• Select by attribute: $('[name="value"]')
2. Chaining Methods: jQuery allows method chaining, where multiple methods can be called on the
same selection. For example:
$('p').addClass('highlight').fadeOut();
4. Event Handling: jQuery simplifies event handling with methods like on(), click(), change(), etc.
For example:
$('button').click(function() {
alert('Button clicked!');
});
5. Animations: jQuery provides animation effects using methods like fadeIn(), fadeOut(),
slideDown(), slideUp(), etc.
6. AJAX: jQuery simplifies AJAX requests with methods like $.ajax(), $.get(), $.post(), etc., for
fetching data from a server asynchronously.
7. Utility Functions: jQuery provides various utility functions for working with arrays, objects,
strings, etc. For example:
• $.each(): Iterate over arrays and objects.
• $.trim(): Trim whitespace from a string.
• $.extend(): Merge the contents of two or more objects together.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
BCA III Year VI Semester – Elements of Commercial Portals
<meta charset="UTF-8">
<title>jQuery Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
// Wait for the document to be ready
$('#myButton').click(function(){
// Handle button click event
$('p').hide(); // Hide all paragraphs
});
});
</script>
</head>
<body>
</body>
</html>
In this example:
• When the document is ready ($(document).ready()), a click event handler is attached to the
button with the ID myButton.
• When the button is clicked, all paragraphs (<p>) on the page are hidden using the hide() method.
2. Document Ready Handler: To ensure that your jQuery code executes only after the DOM
(Document Object Model) has fully loaded, you should wrap your code inside a
$(document).ready() function. This ensures that your code won't run until the HTML document is
completely parsed and loaded. For example:
$(document).ready(function() {
// jQuery code goes here
});
3. jQuery Code: Within the document ready handler, you can write your jQuery code to perform
various tasks such as selecting elements, manipulating the DOM, handling events, etc. Here's where
you'll put the core functionality of your script.
Create a simple jQuery script that changes the text of a paragraph when a button is clicked:
1. Include jQuery library in your HTML file:
<!DOCTYPE html>
<html lang="en">
BCA III Year VI Semester – Elements of Commercial Portals
<head>
<meta charset="UTF-8">
<title>First jQuery Script</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p id="myParagraph">This is a paragraph.</p>
<button id="myButton">Click me</button>
</body>
</html>
2. Write jQuery code within the document ready handler to handle the button click event and
change the text of the paragraph:
<script>
$(document).ready(function() {
$('#myButton').click(function() {
$('#myParagraph').text('Text changed by jQuery!');
});
});
</script>
In this example:
• When the document is ready, the click event handler is attached to the button with the ID myButton.
• When the button is clicked, the text of the paragraph with the ID myParagraph is changed to "Text
changed by jQuery!" using the text() method.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
BCA III Year VI Semester – Elements of Commercial Portals
<meta charset="UTF-8">
<title>Traversing the DOM with jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Parent Traversal
$('#child').parent().css('border', '2px solid red');
// Child Traversal
$('#parent').children().css('background-color', 'lightblue');
// Sibling Traversal
$('#sibling').next().css('font-weight', 'bold');
});
</script>
<style>
div { margin: 10px; padding: 10px; }
</style>
</head>
<body>
<div id="parent">
Parent
<div id="child">Child</div>
<div id="sibling">Sibling</div>
</div>
</body>
</html>
In this example:
• $('#child').parent().css('border', '2px solid red'); selects the parent of the element with ID child
and adds a red border to it.
• $('#parent').children().css('background-color', 'lightblue'); selects all child elements of the
element with ID parent and sets their background color to light blue.
• $('#sibling').next().css('font-weight', 'bold'); selects the next sibling of the element with ID
sibling and sets its font weight to bold.
Example:
$(document).ready(function() {
// Selecting elements by ID
$('#myElement').text('Selected by ID');
// Selecting elements by class
BCA III Year VI Semester – Elements of Commercial Portals
$('.myClass').css('color', 'red');
// Selecting elements by attribute
$('[name="email"]').val('example@example.com');
// Selecting elements by element name
$('input').css('border', '1px solid green');
// Selecting elements by relationship
$('ul > li').addClass('listItem');
});
In this example:
• $('#myElement').text('Selected by ID'); selects an element with ID myElement and changes its
text content.
• $('.myClass').css('color', 'red'); selects all elements with class myClass and changes their text
color to red.
• $('[name="email"]').val('example@example.com'); selects all elements with the attribute
name="email" and sets their value to example@example.com.
• $('input').css('border', '1px solid green'); selects all input elements and adds a green border to
them.
• $('ul > li').addClass('listItem'); selects all li elements that are direct children of ul elements and
adds a class listItem to them.
Example:
Consider the following HTML form:
BCA III Year VI Semester – Elements of Commercial Portals
<form id="myForm">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="remember" id="rememberCheckbox">
<label for="rememberCheckbox">Remember Me</label>
<input type="submit" value="Login">
</form>
1. Filtering Example:
$(document).ready(function() {
// Filter out the input fields with the name 'username'
$('input').filter('[name="username"]').css('border', '1px solid red');
// Select all checked checkboxes and radio buttons and set their border color
$('#myForm :checked').css('border', '1px solid green');
// Select all selected options within select elements and set their border color
$('#myForm :selected').css('border', '1px solid orange');
});
In these examples, jQuery is used to refine selections and apply CSS styles to specific form elements based
on their type, name, or state. This demonstrates how jQuery's powerful selection and filtering capabilities
can be used to manipulate form elements dynamically.
Chaining Methods:
Chaining allows you to apply multiple jQuery methods to the same selection in a single statement, making
your code more concise and readable.
Example of chaining:
$(document).ready(function() {
// Chaining multiple methods
BCA III Year VI Semester – Elements of Commercial Portals
$('p').css('color', 'red').addClass('highlight').fadeOut('slow');
});
In this example:
• $('p') selects all <p> elements.
• .css('color', 'red') sets the text color of selected paragraphs to red.
• .addClass('highlight') adds the class highlight to selected paragraphs.
• .fadeOut('slow') applies a fade-out animation to selected paragraphs with a slow duration.
In this example:
• .val() is used as a getter to retrieve the value of an input field with ID myInput.
• .text() is used both as a setter and a getter to set and retrieve the text content of paragraphs (<p>).
• .html() is used both as a setter and a getter to set and retrieve the HTML content of a <div>.
jQuery's chaining, getters, and setters contribute to its ease of use and expressiveness, allowing developers
to write concise and powerful code for manipulating DOM elements and their properties.
Manipulating Dimensions:
jQuery provides methods to retrieve and modify the dimensions (width, height) of elements on the page.
• Getting Dimensions:
• .width(): Gets the current computed width of the first matched element, including padding
but not border or margin.
• .height(): Gets the current computed height of the first matched element, including padding
but not border or margin.
• .innerWidth(): Gets the current computed width of the first matched element, including
padding but not border, and optionally includes padding.
• .innerHeight(): Gets the current computed height of the first matched element, including
padding but not border, and optionally includes padding.
• .outerWidth(): Gets the current computed width of the first matched element, including
padding and border but not margin, and optionally includes padding and border.
• .outerHeight(): Gets the current computed height of the first matched element, including
padding and border but not margin, and optionally includes padding and border.
• Setting Dimensions:
• .width(value): Sets the width of all matched elements.
BCA III Year VI Semester – Elements of Commercial Portals
• .height(value): Sets the height of all matched elements.
Example:
$(document).ready(function() {
// Get dimensions
var width = $('#myElement').width();
var height = $('#myElement').height();
console.log('Width:', width, 'Height:', height);
// Set dimensions
$('#myElement').width(200);
$('#myElement').height(100);
});
These examples demonstrate how to manipulate CSS properties and dimensions of elements using jQuery,
providing a convenient way to dynamically style and layout elements on your web page.
• Setting Information:
• .text(text): Sets the text content of the selected element.
• .html(html): Sets the HTML content of the selected element.
• .attr(attributeName, value): Sets the value of the specified attribute of the selected
element.
• .val(value): Sets the value of form elements like input, select, and textarea.
Example:
$(document).ready(function() {
// Getting information
var textContent = $('p').text();
console.log('Text Content:', textContent);
// Setting information
$('p').text('New text content');
});
• Copying Elements:
• .clone(): Creates a deep copy of the selected elements, including their descendants.
• Removing Elements:
• .remove(): Removes the selected elements from the DOM.
• .empty(): Removes all child nodes of the selected elements without removing the elements
themselves.
Example:
$(document).ready(function() {
// Moving elements
$('p').appendTo('#target');
$('#source').insertAfter('#target');
// Copying elements
var clone = $('#source').clone();
clone.appendTo('#container');
// Removing elements
$('#elementToRemove').remove();
$('#container').empty();
});
jQuery – II
Manipulating attributes, utilities methods in jQuery
In jQuery, you can manipulate attributes of HTML elements, such as class, id, src, href, etc., using various
methods. Additionally, jQuery provides utility methods for performing common tasks such as iterating over
collections, merging arrays, and handling asynchronous operations.
• Setting Attributes:
• .attr(name, value): Sets the value of the specified attribute for all matched elements.
• .prop(propertyName, value): Sets the value of a property for all matched elements.
• .addClass(className): Adds one or more classes to the matched elements' class attribute.
BCA III Year VI Semester – Elements of Commercial Portals
• .removeClass(className): Removes one or more classes from the matched elements' class
attribute.
• .toggleClass(className): Adds or removes one or more classes from the matched elements
based on their presence.
Example:
$(document).ready(function() {
// Getting attributes
var href = $('a').attr('href');
console.log('Href:', href);
// Setting attributes
$('img').attr('src', 'newimage.jpg');
$('input').prop('disabled', true);
$('div').addClass('highlight');
});
Utility Methods:
• Each Method:
• $.each(array, function(index, value)): Iterates over a jQuery object, executing a function
for each matched element.
• Extend Method:
• $.extend(target, object1, object2, ...): Merges the contents of two or more objects into the
target object.
• Ajax Methods:
• $.ajax(): Performs an asynchronous HTTP request.
• $.get(): Loads data from the server using an HTTP GET request.
• $.post(): Loads data from the server using an HTTP POST request.
Example:
$(document).ready(function() {
// Each method
$('li').each(function(index) {
console.log('Item ' + (index + 1) + ': ' + $(this).text());
});
// Extend method
var obj1 = { a: 1, b: 2 };
var obj2 = { b: 3, c: 4 };
var result = $.extend({}, obj1, obj2);
console.log('Merged Object:', result);
// Ajax method
$.get('example.txt', function(data) {
console.log('Data from server:', data);
BCA III Year VI Semester – Elements of Commercial Portals
});
});
Events - connecting events to elements, namespacing events, event handling, triggering event handlers,
event delegation
In jQuery, events play a crucial role in creating interactive web applications. You can connect events to
elements, handle events, namespace events for better organization, trigger event handlers programmatically,
and use event delegation to efficiently manage events on dynamically created elements. Here's an overview
of these concepts:
Namespacing Events:
Namespacing events is a technique to organize event handlers by prefixing event types with a namespace.
This allows you to easily remove or unbind specific event handlers later.
$(document).ready(function() {
// Connect click event with namespace
$('button').on('click.myNamespace', function() {
alert('Button clicked with namespace!');
});
Event Handling:
You can handle events using event methods such as .on(), .off(), .bind(), .unbind(), etc. These methods
allow you to attach event handlers, detach event handlers, and trigger events programmatically.
$(document).ready(function() {
// Connect event handler
$('input').on('keypress', function(event) {
console.log('Key pressed:', event.key);
});
Event Delegation:
Event delegation allows you to attach a single event handler to a parent element and have it respond to
events that occur on its descendants, even if they are dynamically created after the handler is attached.
$(document).ready(function() {
// Event delegation for dynamically created elements
$('ul').on('click', 'li', function() {
alert('List item clicked!');
});
These examples illustrate how to work with events in jQuery, including connecting events to elements,
namespacing events, handling events, triggering event handlers, and using event delegation. Understanding
these concepts is essential for building interactive and responsive web applications.
Slide:
• .slideDown(): Slides down the matched elements.
• .slideUp(): Slides up the matched elements.
• .slideToggle(): Toggles between sliding down and sliding up the matched elements.
$(document).ready(function() {
// Slide down element
$('#myElement').slideDown();
// Slide up element
$('#myElement').slideUp();
Animate:
• .animate(properties, duration, easing, complete): Performs a custom animation on the matched
elements.
$(document).ready(function() {
// Custom animation
$('#myElement').animate({
width: '200px',
height: '200px',
opacity: 0.5
}, 1000, 'swing', function() {
console.log('Animation complete');
});
});
Callback:
You can specify a callback function to be executed after an animation completes.
$(document).ready(function() {
BCA III Year VI Semester – Elements of Commercial Portals
$('#myElement').fadeOut('slow', function() {
console.log('Fade out complete');
});
});
Stop:
• .stop(): Stops the currently running animation on the matched elements.
$(document).ready(function() {
$('#myElement').stop();
});
These examples demonstrate how to use jQuery effects to animate elements on a web page, including hiding
and showing elements, fading elements in or out, sliding elements up or down, and custom animations. You
can also utilize callback functions to execute code after an animation completes and the stop() method to
stop ongoing animations.
Draggable:
The draggable interaction allows you to make elements draggable by the user. You can specify options to
control the behavior of dragging, such as containment, cursor, and snap.
Example:
$(function() {
$('#draggableElement').draggable();
});
Droppable:
The droppable interaction allows you to define drop targets for draggable elements. You can specify
options to control the behavior of dropping, such as tolerance, accept, and hoverClass.
Example:
$(function() {
$('#droppableArea').droppable({
drop: function(event, ui) {
$(this).addClass('dropped');
ui.draggable.addClass('dragged');
}
});
});
Resizable:
The resizable interaction allows you to make elements resizable by the user. You can specify options to
control the behavior of resizing, such as handles, minWidth, and maxWidth.
Example:
BCA III Year VI Semester – Elements of Commercial Portals
$(function() {
$('#resizableElement').resizable();
});
Selectable:
The selectable interaction allows you to make elements selectable by the user. You can specify options to
control the behavior of selection, such as filter, cancel, and selected.
Example:
$(function() {
$('#selectableContainer').selectable();
});
Sortable:
The sortable interaction allows you to make elements sortable by the user. You can specify options to
control the behavior of sorting, such as axis, containment, and handle.
Example:
$(function() {
$('#sortableList').sortable();
});
These interactions can enhance the user experience of your web applications by providing intuitive ways
for users to interact with elements. You can customize the behavior and appearance of these interactions
using various options provided by jQuery UI.
DatePicker:
The DatePicker widget provides a calendar interface for selecting dates. It allows users to navigate through
months and years, select a specific date, and optionally input dates directly.
Example:
$(function() {
$('#datepicker').datepicker();
});
Menu:
BCA III Year VI Semester – Elements of Commercial Portals
The Menu widget allows you to create hierarchical menus with submenus. You can customize the
appearance and behavior of menu items, such as adding icons, tooltips, and keyboard navigation.
Example:
$(function() {
$('#menu').menu();
});
Tabs:
The Tabs widget organizes content into separate tabs, allowing users to switch between different sections
of content. Each tab panel can contain any HTML content, such as text, images, or other widgets.
Example:
$(function() {
$('#tabs').tabs();
});
These widgets provide rich and interactive user interface elements that enhance the usability and
functionality of web applications. You can customize their appearance and behavior using various options
provided by jQuery UI. Integrating these widgets into your web applications can help improve the user
experience and make your application more user-friendly.
Plugins are typically developed to solve specific problems or add specific functionalities to web
applications. They encapsulate complex or commonly used code into a single unit that can be easily
integrated into projects, making development more efficient and reducing code duplication.
There are thousands of jQuery plugins available, covering a wide range of functionalities such as sliders,
carousels, lightboxes, form validation, Ajax handling, animations, and much more. These plugins are often
developed by the community and shared through various platforms like GitHub, npm, or the jQuery Plugin
Registry.
Using plugins can save developers time and effort by providing pre-built solutions for common tasks,
allowing them to focus on building unique features or solving domain-specific problems in their
applications.
Using Ready-made Plugins:
1. Find a Plugin: Search for a jQuery plugin that fits your requirements on platforms like GitHub,
npm, or the jQuery Plugin Registry.
2. Include jQuery and Plugin Files: Add the jQuery library and the plugin files to your HTML
document.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="path/to/plugin.js"></script>
3. Initialize the Plugin: Initialize the plugin on the appropriate HTML element(s) using JavaScript.
<div id="myElement"></div>
<script>
$(document).ready(function() {
$('#myElement').pluginName();
BCA III Year VI Semester – Elements of Commercial Portals
});
</script>
Creating a Basic Plugin:
1. Define the Plugin Function: Create a function that defines your plugin's behavior. The function
should accept options as parameters and return this to maintain chaining.
(function($) {
$.fn.myPlugin = function(options) {
// Default options
var settings = $.extend({
color: 'red',
fontSize: '16px'
}, options);
// Plugin logic
return this.each(function() {
$(this).css({
color: settings.color,
fontSize: settings.fontSize
});
});
};
})(jQuery);
2. Use the Plugin: Call the plugin function on selected elements and pass any desired options as an
object.
$(document).ready(function() {
$('.myElements').myPlugin({
color: 'blue',
fontSize: '20px'
});
});
Writing Plugins:
1. Define the Plugin Function: Write a function that encapsulates your plugin's functionality. Use
$.fn to extend jQuery with your plugin method.
2. Handle Options: Use $.extend() to merge default options with user-defined options.
3. Implement Plugin Logic: Write the logic for your plugin inside the function. Use this.each() to
iterate over the selected elements.
4. Return this: Ensure that the plugin function returns this to maintain chaining.
5. Initialize the Plugin: Call the plugin function on selected elements in your HTML document.
By following these steps, you can either use ready-made plugins or create your own custom jQuery plugins
to add specific functionalities to your web applications.
2. Slick: A responsive carousel/slider plugin that supports various options and configurations for
creating slick and customizable carousels.
3. FancyBox: A lightweight and customizable lightbox plugin for displaying images, videos, or HTML
content in a modal window with various transition effects.
4. jQuery Validation Plugin: A plugin for client-side form validation that provides a robust set of
validation rules and customizable error messages.
5. Select2: Enhances HTML select boxes by adding search functionality, tagging support, infinite
scrolling, and other features to create rich and user-friendly select inputs.
6. DataTable: Allows you to enhance HTML tables by adding advanced features such as sorting,
filtering, pagination, and more, making it easy to work with large datasets.
7. Chosen: A plugin for enhancing select boxes and multiple select inputs by adding search
functionality, keyboard navigation, and customizable styling.
8. jQuery Mask Plugin: Provides a simple way to mask input fields (e.g., for formatting phone
numbers, dates, or credit card numbers) by defining input patterns.
9. jQuery ScrollTo: Allows smooth scrolling to specific elements on a page or to specific positions
within the document, enhancing navigation and user experience.
10. Waypoints: A library that triggers events when scrolling to specific elements on the page, allowing
for dynamic behavior such as lazy loading, infinite scrolling, or animations.
These are just a few examples of the many jQuery plugins available. They demonstrate the versatility and
power of jQuery in extending the functionality of web applications and enhancing user experience.
Depending on your project requirements, you can choose from a wide range of plugins to add desired
features and functionalities to your web application.
BCA III Year VI Semester – Elements of Commercial Portals
Unit V - AJAX
AJAX introduction
AJAX (Asynchronous JavaScript and XML) is a technology used to create interactive and dynamic web
applications by enabling asynchronous communication between the client and the server. It allows web
pages to request and exchange data with a server in the background without requiring the page to be
refreshed or reloaded.
2. XMLHttpRequest Object: In traditional web development, the primary way to interact with the
server was through full-page reloads initiated by hyperlinks or form submissions. AJAX introduced
the XMLHttpRequest (XHR) object, which allows JavaScript code to make HTTP requests to the
server asynchronously.
3. Data Exchange Formats: AJAX typically exchanges data with the server in formats such as JSON
(JavaScript Object Notation) or XML (eXtensible Markup Language). JSON has become the
preferred format due to its simplicity, lightweight nature, and ease of parsing in JavaScript.
4. DOM Manipulation: Upon receiving a response from the server, AJAX allows JavaScript to
dynamically update the content of the web page without reloading the entire page. This is often
achieved by manipulating the Document Object Model (DOM) of the webpage.
6. Cross-Origin Resource Sharing (CORS): Due to security restrictions enforced by web browsers,
AJAX requests are subject to the same-origin policy, which prohibits requests to domains other than
the one from which the web page originated. CORS is a mechanism that allows servers to specify
which origins are permitted to access their resources via AJAX requests.
1. $.ajax():
This is the most flexible method for making AJAX requests. It allows you to specify various options such
as the URL, request type (GET, POST, etc.), data to send to the server, and callbacks for success, error, and
complete events.
$.ajax({
url: 'example.com/api/data',
method: 'GET',
data: { key: 'value' },
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
2. $.get()
This method is a shorthand for making GET requests. It takes the URL to which the request is sent and an
optional data object, and it returns the response data.
$.get('example.com/api/data', { key: 'value' }, function(response) {
console.log('Data received:', response);
});
3. $.post()
Similarly, this method is a shorthand for making POST requests. It takes the URL to which the request is
sent, data to send to the server, and a callback function to handle the response.
$.post('example.com/api/data', { key: 'value' }, function(response) {
console.log('Data received:', response);
});
4. $.getJSON()
This method is specifically for making AJAX requests for JSON data. It is a shorthand for making GET
requests with JSON as the expected response type.
$.getJSON('example.com/api/data', { key: 'value' }, function(response) {
console.log('JSON data received:', response);
});
5. $.ajaxSetup()
This method is used to set default values for future AJAX requests. It allows you to specify default settings
such as the URL, type, and headers for all AJAX requests made with jQuery.
$.ajaxSetup({
BCA III Year VI Semester – Elements of Commercial Portals
url: 'example.com/api',
type: 'POST'
});
6. $.ajaxPrefilter()
This method allows you to modify AJAX requests before they are sent to the server or responses before
they are processed. It is useful for adding custom headers, manipulating request data, or handling responses
globally.
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
// Add custom headers
options.headers = options.headers || {};
options.headers['X-CSRF-Token'] = 'your_csrf_token';
});
<script>
$(document).ready(function() {
$('#myForm').submit(function(event) {
// Prevent default form submission
event.preventDefault();
Integrating AJAX with forms can enhance the user experience by providing real-time feedback, reducing
page reloads, and improving overall responsiveness.
AJAX Events
In jQuery, AJAX requests trigger several events at different stages of the request's lifecycle. These events
provide hooks for executing code before or after specific actions, such as before the request is sent, when
the request completes successfully, or when an error occurs.
Overview of some common AJAX events and how to use them with suitable examples:
1. beforeSend
This event is triggered before the AJAX request is sent to the server. It allows you to modify the request
headers or perform any setup tasks.
Example:
$.ajax({
url: 'example.com/data',
method: 'GET',
beforeSend: function(xhr) {
// Add custom headers
xhr.setRequestHeader('Authorization', 'Bearer token123');
},
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
2. success
This event is triggered when the AJAX request completes successfully and the server responds with a 2xx
status code. It provides access to the response data.
Example:
$.ajax({
url: 'example.com/data',
method: 'GET',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
BCA III Year VI Semester – Elements of Commercial Portals
3. error
This event is triggered when an error occurs during the AJAX request, such as a network error or a server
error (status code other than 2xx). It provides information about the error.
Example:
$.ajax({
url: 'example.com/data',
method: 'GET',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
} });
4. complete
This event is triggered after the AJAX request completes, regardless of whether it was successful or resulted
in an error. It can be used for cleanup tasks or to execute code after the request finishes.
Example:
$.ajax({
url: 'example.com/data',
method: 'GET',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
},
complete: function(xhr, status) {
console.log('Request complete:', status);
}
});