PHP-MySQL Series

Chapter-1 Introduction to PHP MySQL Part 1

Client Server Architecture :

Client-Server Architecture:

  1. Definition: It's a way to organize computers in a network where one computer (the client) requests services or resources, and another computer (the server) provides those services or resources.

Key Components:

  1. Client:

    • Role: The client is a device or application that requests services or resources.

    • Examples: Your web browser (like Chrome or Firefox) is a client when you use it to visit a website.

  2. Server:

    • Role: The server is a powerful computer or application that provides services or resources.

    • Examples: The computer hosting a website is a server. When you visit a website, the server sends the web pages to your browser.

How It Works:

  1. Request: The client sends a request to the server.

    • Example: When you type a web address (like www.example.com) in your browser and press Enter, your browser sends a request to the server hosting that website.
  2. Response: The server processes the request and sends back a response.

    • Example: The server hosting www.example.com sends the web page back to your browser, which then displays it.

Real-Life Analogy:

  • Restaurant:

    • Client: You, the customer, who orders food.

    • Server: The kitchen, which prepares and provides the food.

    • Process: You (the client) order a dish, the kitchen (the server) prepares it and then serves it to you.

In summary, in a client-server architecture, the client requests services or resources, and the server provides them. This setup is commonly used in web browsing, email, and many other internet applications.

Client-Server Architecture | Types Of Client Server Architecture - Tech Blog

• Web Browser is a Client

• Web Server is a Server

Why PHP :

Easy to learn

Best suited for rapid application development

Easy to implement

PHP community is a big support for PHP is the most the programmers.

Runs on almost every platform

It is free

Web hosting :

How Does Web Hosting Work? A 4-Step Breakdown

• Web hosting is the storage of your website pages on some server machine.

Web Hosting:

  1. Definition: Web hosting is a service that allows you to put your website on the internet so people can visit it.

Key Components:

  1. Website Files: These are the files that make up your website, like HTML pages, images, and videos.

  2. Web Host: A company that provides space on its servers to store your website files and makes them available on the internet.

  3. Server: A powerful computer that stores your website files and sends them to people's browsers when they visit your site.

How It Works:

  1. You Create a Website: You design and build your website using tools like HTML, CSS, and images.

  2. Choose a Web Host: You select a web hosting company to store your website files. Popular web hosts include Bluehost, HostGator, and GoDaddy.

  3. Upload Your Files: You upload your website files to the web host's server.

  4. Domain Name: You get a domain name (like www.example.com) that points to your website files on the server.

  5. Visitors Access Your Site: When someone types your domain name in their browser, the browser requests the files from the web host's server, and your website appears on their screen.

Real-Life Analogy:

  • Library:

    • Books: Your website files.

    • Library: The web host.

    • Library Shelves: The server.

    • Library Address: Your domain name.

    • Visitors: People who come to read the books.

In summary, web hosting is like renting space in a library for your books. The web host (library) stores your website files (books) on its servers (shelves) and uses a domain name (library address) to make your site available to visitors on the internet.

Web Pages :

• A web page is a plain text document with formatting instructions of Hyper Text Markup Language (HTML), which is interpreted by Web browser. Web pages are transported and accessed by HyperText Transfer Protocol (HTTP)

or

webpages are nothing it's a simple html pages

<html>

<head>

</head>

<body>

<!-- ... -->

</body>

</html>

Chapter-1 Introduction to PHP MySQL Part 2

Conversation :

A client, commonly a web browser, initiates communication by making a request for a specific resource using HTTP and the server responds with the content of that resource or an error message if unable to do so.

How data flow from Web Browser to Web Server

  1. Client (Web Browser) Request: When you want to visit a website, you type its address (like www.example.com) into your web browser and press Enter.

  2. HTTP Request: Your web browser sends a message (request) over the internet asking the server (where the website is stored) to send the web page you want to see. This message is sent using a protocol called HTTP (HyperText Transfer Protocol).

  3. Server Response: The server receives the request and looks for the web page you asked for.

    • Success: If the server finds the page, it sends it back to your web browser.

    • Error: If the server can't find the page or something goes wrong, it sends back an error message (like a 404 error if the page doesn't exist).

  4. Displaying the Page: Your web browser gets the web page from the server and shows it to you on your screen.

So, in simple terms:

  • You ask for a web page.

  • The server finds and sends the page to you.

  • If there’s a problem, the server tells you there’s an error.

    1. Web Server: A web server is a computer that stores websites. It can also mean the software on that computer that helps send web pages to people.

    2. How It Works: When you visit a website, your web browser talks to the web server. This conversation has two parts:

      • HTTP Request: Your web browser asks the web server for a web page.

      • HTTP Response: The web server sends the web page back to your browser.

So, a web server is like a waiter that brings you the web pages you ask for, and each time you ask for a page, it's a little conversation between your browser and the server.

Website :

All the websites you can visit on the internet together make up what we call the World Wide Web, or just the Web. It's like a huge collection of web pages that anyone can access using a web browser.

A web site is hosted at least on one web server accessible via network such as the internet or local area network (LAN) through an internet address known as a uniform resource locator.

  • or

    website are nothing it's a collection of webpages

Web Browser :

  1. Web Browser: A web browser is a program you use to look at websites on the internet. It's like a window that lets you see and interact with web pages.

  2. What Browsers Do: When you want to visit a website, the web browser helps you find it, shows it to you, and lets you click on links to go to other pages.

  3. URL: Every website has its own address called a URL (Uniform Resource Locator). It's like the website's home address on the internet.

  4. Examples of Browsers: Some popular web browsers you might know are:

    • Mozilla Firefox

    • Google Chrome

    • Internet Explorer

    • Opera

    • Safari

These browsers help you find and look at web pages on the World Wide Web.

Web Server :

  1. Web Server: A web server can mean two things:

    • Hardware: The physical computer that stores website information.

    • Software: The program on that computer that helps send website information to your web browser.

      or

      webserver are nothing it's just store the website information .

  2. What Web Servers Do: Web servers have three main jobs:

    • Hosting Websites: They keep all the files and information for websites so people can visit them.

    • Data Storage: They store data that people can access online.

    • Enterprise Applications: They run special programs for businesses that people can use over the internet.

    • Main Job of Web Servers: Web servers have a main job: sending web pages to you when you ask for them.

    • What They Send: When you want to see a web page, the web server sends:

      • HTML Documents: The main part of the web page that has the text and structure.

      • Images: Pictures included in the web page.

      • Style Sheets (CSS): Instructions on how the page should look (like colors and layout).

      • JavaScript: Extra bits of code that make the page interactive and dynamic.

So, web servers make sure you get the complete web page with all its parts when you visit a website.

Example of web server :

  1. Apache: Apache is a very popular program that many websites use to manage and deliver their web pages. It's like one of the most common tools for running websites.

  2. Microsoft's Internet Information Services (IIS): IIS is another widely used program by Microsoft that helps websites run and deliver their pages.

So, when you visit websites, many of them are using either Apache or IIS to make sure the web pages work properly and get sent to your browser.

World Wide Web :

In 1994, Tim Berners-Lee decided to constitute the World Wide Web Consortium (W3C) to regulate the development of the many technologies involved (HTTP, HTML, etc.) through a standardization process.

static web page :

A static web page has fixed content

It does not require programming languages to build one.

It is the easiest form of website to create.

Static websites are build of HTML, CSS, and JavaScript.

Dynamic Web Page :

A dynamic web page is generated by some web application.

Dynamic web page displays user specific content.

They are generated by program which could be written in PHP.

or

A Dynamic webpages has no fixed content.

A static website has fixed content**Database Server :**

• A database server is a computer program that provides database services to other computer programs or computers, as defined by the client server model.

• The term may also refer to a computer dedicated to running such a program.

• Some examples of database servers are Oracle, DB2, SQL server, MySQL

• The SQL query language is more or less same in all the database servers.

Chapter-2 Introduction to HTML

Here are the basics of HTML in a simple and concise manner:

  1. HTML: Stands for HyperText Markup Language.

  2. Structure: Used to structure content on the web.

  3. Tags: HTML elements are defined by tags (e.g., <tagname>).

  4. Document: Every HTML document starts with <!DOCTYPE html>, followed by <html>.

  5. Head: Contains meta-information inside <head>, such as <title>, <meta>, and <link>.

  6. Body: The main content is placed inside <body>.

  7. Headings: Defined using <h1> to <h6> tags.

  8. Paragraphs: Defined using the <p> tag.

  9. Links: Created using the <a> tag with href attribute.

  10. Images: Embedded using the <img> tag with src attribute.

  11. Lists: Ordered lists (<ol>) and unordered lists (<ul>), with list items (<li>).

  12. Tables: Created using <table>, with rows (<tr>), headers (<th>), and data cells (<td>).

  13. Forms: Created using <form>, with input fields like <input>, <textarea>, <button>, etc.

  14. Div and Span: Used to group elements. <div> for block-level, <span> for inline.

  15. Attributes: Provide additional information about elements (e.g., class, id, style).

Introduction to HTML Hyper Text Markup Language

• HTML is case insensitive language

• HTML uses markup tags to define a web page

• HTML file has an extension.htm or.html

• HTML is developed by World Wide Web Consortium

Currently using HTML 5

HTML elements :

An HTML element is an individual component of an HTML document.

It starts with a start tag / opening tag and ends with an end tag / closing tag

The element content is everything between the start and the end tag Most.

HTML elements can have attributes (Properties)

Example :

<p>This is a paragraph </p>

Here,

<p>is starting tag and </p> is closing tag.

Everything between them is paragraph content to be displayed on browser

Document Structure Elements

• All HTML documents must start with a type declaration : <!doctype html >

<html>

<head>

<body>

html tag :

• The Root element of an HTML document; all other elements are contained in this

• The HTML element delimits the beginning and the end of an HTML document.

head tag:

• Container for processing information and metadata for an HTML document.

body tag :

• Container for the displayable content of an HTML document.

Format :

<!doctype>

<html>

<head>

Place processing information and metadata here

</head>

<body>

Place displayable content here

</body>

</html>

comment :

<!--

Write your comment here

-->

Chapter-3 HTML Tags

Title tag :

• It is written in <head> tag .

• The <tittle> tag defines the title of the document .

• It defines a title in the browser toolbar .

• It provides a title for the page when it is added to favorites.

• It displays a title for the page in search-engine results.

Heading tags :

• Headings are defined with the <h1> to <h6> tags

• <h1> defines the most important heading.

• <h6> defines the least important heading

• Search engines use your headings to index the structure and content of your web pages

Paragraph tag :

• Paragraphs are defined with the <p> tag

• Browsers automatically add an empty line before and after a paragraph.

Formatting tags :

<br/> - Break Line

• Use the <br/> tag if you want a line break (a new line) without starting a new paragraph:

• The < br/> element is an empty HTML element.

• It has río end tag.

<hr/> - Horizontal Line

• The <hr/> tag creates a horizontal line in an HTML page.

• The <hr/> element can be used to separate content.

Image tag :

• Images are defined with the <img> tag

• The <img> tag is empty, which means that it contains attributes only, and has no closing tag.

• To display an image on a page, you need to use the src attribute. src stands for "source". The value of the src attribute is the URL of the image you want to display.

<img src="https://images.pexels.com/photos/2286895/pexels-photo-2286895.jpeg?cs=srgb&dl=pexels-rfera-2286895.jpg&fm=jpg"
       border="2px" width ="500" height ="300"alt="Beautiful Landscape" 
       align="right">

Attributes of the image tag :

• Src = some url for image

• Alt = alternative text

• Width = pixel or percentage

• Height = pixel or percentage

• Align = top, bottom, middle, left, right

• Border = pixel

List tags :

• Two types of List

  • Unordered List :

    - An unordered list starts with the <ul/> tag

    - Each list item starts with the <li/> tag

    - The list items are marked with bullets (typically small black circles).

    Attribute type :

    • Attribute type has following values

    - square

    - disc

    - circle

  • Ordered List :

    • The <ol> tag is used to create an ordered list.

    • The list can be numerical or alphabetical.

    Attribute type :

• Attribute type has following values

-1

-A

- a

-i

-I

<Ul type = "circle">
        <li>java</li>
        <li>c</li>
        <li>c++</li>
      </Ul>
     <ol type = "a">
        <li>java</li>
        <li>c</li>
        <li>c++</li>
      </ol>

Anchor tag :

• A hyperlink (or link) is a word, group of words, or image that you can click on to jump to a new document or a new section within the current document.

• Links are specified in HTML using the <a> tag

<a href = "URL" > MY PIC </a>

Chapter-4 HTML Table Tag

Table tag :

• <table> - defines a table

•<th>- Defines a table header

•<tr> - Defines a row in a table

• <td> - Defines table data

Attributes of table tag :

• border (It specifies the width of the border around a table)

• cellpadding (Specifies the space between the cell wall and the cell content)

• cellspacing (Specifies the space between cells)

• align (values can be left, center or right)

• width (specifies the width of a table)

• bgcolor (specifies a background color of a table)

- Color name ("pink")

- Hex code of color name ("#ffA000")

- rgb number ("rgb(255,0,0)")

Attributes for <th> and <td>

• align =left, right, center, justify

• bgcolor =color name, rgb(), hex code

• colspan =number (Marge more row and comoumn)

• rowspan=number

• height =pixel or percentage

• valign=top, middle, bottom

• width =pixel or percentage

!DOCTYPE html>
<html>
<head>
    <title>TABLE</title>
</head>
<body>
    <table border="2px" bgcolor ="pink" 
       align = "center" cellspacing = "0px"  cellpadding = "3px" 
       width = "500px"  >

        <tr>
            <th>S.NO</th>
            <th>NAME</th>
            <th>AGE</th>
        </tr>
        <tr>
            <td>01</td>
            <td>safia</td>
            <td>20</td>
        </tr>
        <tr>
            <td>02</td>
            <td>samir</td>
            <td>1</td>
        </tr>
        <tr>
            <td>03</td>
            <td>samaira</td>
            <td>2</td>
        </tr>
        <tr>
            <td colspan = "3">Total 3 person </td>
        </tr>
       </table>
</body>
</html>

Chapter 5 HTML Form Tag

Ways to send request to Server :

  1. Through URL writing in Browser

  2. Hyperlink <a href="URL"> MY LINK </a>

  3. Form

  4. Ajax

Form Tag :

• HTML forms are used to pass data to a server.

• A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more.

• A form can also contain select lists, textarea, fieldset, legend, and label elements.

• The most important form element is the input element.

Attributes of Form tag :

• Action :

- The required action attribute specifies where to send the form-data when a form is submitted.

• Method :

- Specifies how to send form-data.

- The form-data can be sent as URL variables (with method="get") or as HTTP post (with method="post").

Tags within the form tag

• <input>

• <button>

• <option>

•<select>

•<textarea>

<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
    <form action="somefile.php" method="post">
        <table>
            <tr>
            <th> NAME </th>
            <td> <input type ="text" name="username"/> </td>
        </tr>

             <tr>
            <th> PASSWORD </th>
            <td> <input type = "password" name="password" /> </td>
            </tr>

            <tr>
                <th> Gender </th>
                <td> <input type ="radio" name="Gender"/> Male </td> 
                <td> <input type ="radio" name="Gender"/> Female </td>    
            </tr>

            <tr>
                <th> Course </th>
                <td> <input type="checkbox" name="Php" />Php</td>
                <td><input type="checkbox" name="Java" />Java</td>
                <td><input type="checkbox" name="C++"/>C++</td>
            </tr>

            <tr>
                <th> City </th>
                <td>
                    <select>
                    <option>RANCHI</option>
                    <option>HYDRABAD</option>
                    <option>Dhanbad</option>
                </select>
                </td>
            </tr>
            <tr>
                <td><input type="submit" value ="Register"/></td>
            </tr>

            <tr>
                <td><input type="reset" /> </td>
            </tr>

        </table>
    </form>
</body>
</html>

Chapter-6 iframe in HTML

iframe :

• An iframe is used to display a web page within a web page

• Tag is :

- <iframe>

• Attribute: src

- <iframe src="URL"</iframe>

<!DOCTYPE html>
<html>
<head>
    <style>
        iframe
        {
            width: 100%;
            height: 300px;
        }

    </style>

    <title>Iframe</title>
</head>
<br>
    <iframe src="https://www.mysirg.com/courses/php-mysql/" name="myframe"></iframe>
    <br/>
    <a href="https://www.mysirg.com/courses/php-mysql/" target="myframe">My Website</a> </br>
    <a href="https://www.google.com/search?q=new+2024+song+list&rlz=1C1CHBF_enIN1084IN1088&oq=&gs_lcrp=EgZjaHJvbWUqCQgDECMYJxjqAjIJCAAQIxgnGOoCMgkIARAjGCcY6gIyCQgCECMYJxjqAjIJCAMQIxgnGOoCMgkIBBAjGCcY6gIyCQgFECMYJxjqAjIJCAYQIxgnGOoCMgkIBxAjGCcY6gLSAQk1NzM2ajBqMTWoAgiwAgE&sourceid=chrome&ie=UTF-8" target="myframe">Songs </a>

</body>
</html>

Chapter-1 Introduction to CSS

here are some key points about CSS (Cascading Style Sheets) :

  1. Purpose: CSS is used to style and layout web pages.

  2. Selectors: CSS selects HTML elements to apply styles using selectors (e.g., .class, #id, element).

  3. Properties: Styles are defined using properties (e.g., color, font-size, margin).

  4. Values: Properties have values (e.g., color: red;, font-size: 16px;).

  5. Syntax: The basic syntax is selector { property: value; }.

  6. Cascading: CSS rules can override each other based on specificity and order.

  7. Box Model: Elements are modeled as boxes with content, padding, border, and margin.

  8. Responsive Design: CSS allows for responsive design using media queries (@media).

  9. External Style Sheets: CSS can be written in separate files and linked using <link> tags in HTML.

  10. Inheritance: Some CSS properties are inherited from parent elements to children.

CSS is CSS?

• CSS is Cascading Style Sheet

What is the role of CSS?

• CSS defines how to display HTML elements

Who developed CSS?

• The World Wide Web Consortium (W3C) created CSS

we use css to set : decoration & positions

Current Version

• Currently we are using CSS 3

Where to write CSS?

• We can write CSS in a separate file and link it to our HTML file or embed CSS in HTML file itself

• External Style Sheet

• Internal Style Sheet

• Inline Style

Chapter-2 CSS Syntax

CSS Syntax

ElementSelector

{

PropertyName:PropertyValue;

PropertyName:PropertyValue;

PropertyName:PropertyValue;

}

Element Selector

• ElementSelector is used to specify an HTML element or group of HTML elements on which properties are applied

• There are three ways to specify an Element Selector

- Tag Name

This is tag name used in HTML. This causes selection of all elements with the specified tag name

- Id Value

Id value is unique for HTML elements, so it is used to select a specific element. Id value is prefixed with hash (#) symbol when mentioned in selector

- Class Value

Class value can be common to multiple heterogeneous HTML elements, which causes selection of more than one HTML elements

PropertyName:PropertyValue

• PropertyName is the name of the CSS property name followed by colon (:) and then property value

• We can write one or more property declaration in the block.

Chapter-3 External Style Sheet in CSS

External Style Sheet

• External style sheet is a separate file of CSS

• File must be saved with .css extension

• File contains no tag and only contains css codes

• File can be used to apply on several html files

• External Style Sheet is useful when properties need to be applied on more than one web page of the site


p
{
    color: navy;

}

h1
{

    color: aqua;
    text-decoration: underline;
}
#p1{
color: chocolate;
font-size: 20px;
}

.c1
{
    color: chartreuse;
    background-color: brown;
    font-size: large;
    border-color: cyan;
}

Chapter-4 Internal Style Sheet in CSS

Internal Style Sheet

• Internal style sheet means when CSS is included in the same html file

• <style> tag must be used to write CSS in html file.

• <style> tag should be in <head> tag.

• Type attribute of style tag specify the type of MIME type ( text/css)

• Internal style sheet is useful when page specific properties need to be applied.

• Preference is given to internal style sheet over external style sheet.

Chapter-5 Inline Style in CSS

Inline Style

• Style attribute can be used with tag representing html element

• The value of style attribute is any CSS property.

• Example :

<p style="color: crimson; font-size: 30px;"> This is my first paragraph </p>

• Each property name-value pair is terminated with a semicolon.

• Inline style has more preference given than internal or external style.

• Inline style is useful when element specific property needs to be applied.

Chapter-6 How to change color of text in CSS

• The color property is used to set the color of the text.

Example:

- body {color:blue;}

- h1 {color:#00ff00;}

- h2 {color:rgb(255,0,0);}

style type="text/css">
            h2{
                color: ghostwhite;
                background: #000;
                text-align: center;
                border: blue;
            }
        </style>

Chapter-7 How to set alignment of text in CSS

• The text-align property is used to set the horizontal alignment of a text.

• Text can be centered, or aligned to the left or right, or justified.

h1 {text-align:center;}

<head>
    <style type="text/css">
        p
        {
            text-align: middle;
        }

    </style>

</head>

Chapter-8 How to underline text using

Decorating text

• The text-decoration property is used to set or remove decorations from text.

a {text-decoration:none;}

h1 {text-decoration:overline;}

h2 {text-decoration:line-through;}

h3 {text-decoration:underline;}

<style type="text/css">
        p
        {
            text-align: middle;
            text-decoration: underline;
            color: brown;
        }
        a{
            text-decoration: none;
        }

    </style>

Chapter-9 How to convert text into uppercase using CSS

Text Transformation

• The text-transform property is used to specify uppercase and lowercase letters in a text.

p.uppercase {text-transform:uppercase;}

p.lowercase {text-transform:lowercase;}

p.capitalize {text-transform:capitalize;}

<style type="text/css">
        p
        {
            text-align: middle;
            text-decoration: underline;
            color: brown;
            text-transform: capitalize;
        }
        a{
            text-decoration: none;
        }
        h{
            text-transform: lowercase;
        }

    </style>
Dusra hmlog group bna k v ker sakte hai

 .group{
            text-transform: uppercase;
            color:white;
            box-flex-group: red;
            background-color: black;
            text-decoration: none;
        }
<p class="group"> hiii my self safia i'm from jharkhand </p>

    <h class="group"> This is my first heading </h>

    <p> hiii my self safia i'm from jharkhand </p>

Chapter-10 How to make text italic using

• The font-style property is mostly used to specify italic text.

• This property has following values:

- normal - The text is shown normally

- italic - The text is shown in italics

 font-style: italic;

Chapter-11 How to change size of text using CSS

• The font-size property sets the size of the text.

p{font-size:24px;}

p
{
font-size: 20px;
}

Chapter-12 How to make text bold using CSS

• The font-weight property sets the boldness of the text

p{font-weight:bold;}

p
{
font-weight: bold;
}

agar apko koi particular word ko bold krna ho tab ap span use karo

#s1{
    font-weight: bold;
}
        <p>hiii my self safia <span id="s1">i'm from jharkhand </span></p>

Chapter-13 How to change font of text using CSS

Changing the font

• The font family of a text is set with the font- family property.

Example :

p{font-family:"Georgia";}

  <style type="text/css">

            p{
                font-family:"Verdana";
            }
        </style>

Chapter-14 How to make shadow of text using CSS

Shadow effect to the text

• The text-shadow property applies shadow to text.

• text-shadow:h-shadow v-shadow blur color;

P {

text-shadow:20px 20px 5px gray;

}

<style type="text/css">
        h1{

            text-shadow: 2px 6px 5px red;
            color: black;
            text-align:center;
            text-decoration: underline;
            font-family:"Verdana";
            background-color: yellow;


    </style>

Chapter-15 How to set space between lines and characters in CSS

Space between lines

• It specifies space between the lines of a paragraph text.

line-height: 0.8;

Space between the characters

• It specifies the space between the letters of a text.

• letter-spacing: 2px;

Space between the words

• It specifies space between the words

• word-spacing: 6px;

<style type="text/css">
        p{
            line-height:1.2;
            letter-spacing:2px;
            word-spacing: 6px;
        }

    </style>

Chapter-16 How to set border style, color, width, radius in CSS

border-style

• Every html element that consumes space in the web page is a rectangular region

• This rectangular region can be bordered using css properties

• Border-style property allows you to choose one from the various styles of the border

• Possible values of border-style:

  • solid

  • dotted

  • dashed

  • double

  • groove

  • inset

  • outset

    border-color

    • It specifies the color of the border

  • • border-color: blue;

border-width

• This property specifies the width of the border

• border-width:5px;

border-radius

• Border-radius makes corner curved

• border-radius: 4px;

Individual side

• border-left-style :dashed;

• border-left-color:green;

<style type="text/css">

        h1{
            border-style: solid;
            border-radius: 20px;
            border-color: brown;
            border-width: 10px;
            border-top-left-radius: 10px;
            border-right: 5px;
            border-left: 5px;
            border-left-style: groove;
            border-top-style: dotted;
            border-top-color: chocolate;
            color: darkblue;
            border-style: dashed dotted solid inset; 
            border-left-color: chartreuse;
            border-right-color: cornflowerblue;
            border-top-color: crimson;

        }

    </style>

Chapter-17 How to set background color in CSS

background-color

• Every html element that consumes space in the web page is a rectangular region

• This rectangular region can be filled with specific color

• background-color: #419DFF;

<head>
    <style type="text/css">
h1{
    background-color: aqua;

}

body{
    background-color: yellow;
}

    </style>


</head>

Chapter-18 How to set background image in CSS

background-image

• Every html element that consumes space in the web page is a rectangular region

• This rectangular region can be filled with specific image.

background-image:url('image-file.jpg');

<style type="text/css">


body{
    background-image: url('safia.jpg');
    background-repeat: no-repeat;
    background-repeat: repeat-x;
    background-repeat: repeat-y;

}

    </style>

Chapter-19 How to set width and height in CSS

Width and height

• Every html element that consumes space in the web page is a rectangular region

• We can set width and height of this rectangular region

• width: 100px;

• height: 50px;

 <style type="text/css">
        p{
            background-color: aqua;
            width: 200px;
            height: 250px;
        }
    </style>

Chapter-20 How to set margin and padding in CSS

• margin: 10px;

• padding: 5px;


    <style type="text/css">

        ul{
            background-color: khaki;
            border: 5px solid red;
            margin: 10px;
            padding: 20px;


        }

    </style>

Chapter-21 Anchor properties in CSS

• a:link - a normal, unvisited link

• a:visited - a link the user has visited

• a:hover - a link when the user mouses over it

• a:active - a link the moment it is clicked

<style type="text/css">

    a:link {
        color: green;
    }

    a:hover
    {
        color: aqua;
    }

    a:visited{
        color: cornflowerblue;
    }

    a:active{
        color: red;
    }
   </style>

Chapter-22 How to set position of HTML elements in CSS

Why positioning is important?

By default, HTML elements appear on the web page in the same sequence as they are in the HTML code

HTML is not capable to set position of HTML element with precision

Position property

The position property specifies the type of positioning method used for an element

• position: static; /* default */

• position: fixed;

• position: relative;

• position: absolute;

Positioning

• Elements are then positioned using the top, bottom, left, and right properties.

• These properties will not work unless the position property is set first (value should not be static)

• They also work differently depending on the position value.

static

• HTML elements are positioned static by default

• Top, left, bottom, right properties will not work

• Elements appear according to the normal flow

fixed

• Elements with position fixed always stays in the same place even if the page is s scrolled.

• Top, left, right, bottom will work

relative

• An element with position: relative; is positioned relative to its normal position.

• Top, left, right, bottom will work

absolute

• A "positioned" element is one whose position is anything except static

• An absolute positioned element is positioned relative to the nearest positioned ancestor I

• If an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling

Z-index

• When elements are positioned, they can overlap other elements

• The z-index property specifies the stack order of an element An element with greater stack order is always in front of an element with a lower stack order

• If two positioned elements overlap without a z-index specified, the element positioned last in the HTML code will be shown on top

Notes :

  • Static Positioning (position: static;):

    • This is the default position value. Elements are positioned according to the normal flow of the document.
  • Relative Positioning (position: relative;):

    • The element is positioned relative to its normal position. You can use the top, right, bottom, and left properties to adjust the position relative to its starting point.
  • Absolute Positioning (position: absolute;):

    • The element is positioned relative to the nearest positioned ancestor (an ancestor with a position other than static). If there is no such ancestor, the element is positioned relative to the initial containing block (usually the <html> element).
  • Fixed Positioning (position: fixed;):

    • The element is positioned relative to the viewport, which means it stays in the same place even when the page is scrolled.
  • Sticky Positioning (position: sticky;):

    • The element is treated as relative until it crosses a specified threshold, at which point it is treated as fixed.
  1. Static: The static element appears in the normal document flow.

  2. Relative: The relative element is moved 20px down and 20px right from its original position.

  3. Absolute: The absolute element is positioned 100px from the top and 100px from the left of its nearest positioned ancestor or the initial containing block.

  4. Fixed: The fixed element stays in the same place relative to the viewport, even when scrolling.

  5. Sticky: The sticky element sticks to the top of the page when you scroll past it.

You can adjust the top, right, bottom, and left properties to fine-tune the positioning of elements as needed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Positioning Example</title>
    <link rel="stylesheet" href="position.css">
</head>
<body>
    <div class="static">Static</div>
    <div class="relative">Relative</div>
    <div class="absolute">Absolute</div>
    <div class="fixed">Fixed</div>
    <div class="sticky">Sticky</div>
</body>
</html>
body {
    height: 2000px; /* Just to demonstrate scrolling */
}

div {
    padding: 20px;
    margin: 10px;
    color: white;
}

.static {
    position: static;
    background-color: blue;
}

.relative {
    position: relative;
    top: 20px;
    left: 20px;
    background-color: green;
}

.absolute {
    position: absolute;
    top: 100px;
    left: 100px;
    background-color: red;
}

.fixed {
    position: fixed;
    top: 10px;
    right: 10px;
    background-color: purple;
}

.sticky {
    position: sticky;
    top: 0;
    background-color: orange;
}

Chapter 1 Introduction to JavaScript

JavaScript :

• JavaScript is a high-level, dynamic, and interpreted programming language that is widely used in web development

  • Client-Side Scripting: JavaScript is primarily used to create interactive effects within web browsers. It allows developers to add dynamic behavior to web pages, such as form validation, interactive maps, and animated graphics.

  • Server-Side Scripting: With the advent of environments like Node.js, JavaScript is also used on the server side, allowing developers to build scalable and efficient backend applications.

  • Object-Oriented and Functional Programming: JavaScript supports both object-oriented and functional programming paradigms, making it versatile for different types of software development.

  • Event-Driven: JavaScript is event-driven, meaning it can respond to user interactions or other events like mouse clicks, key presses, and network responses.

  • Interpreted Language: JavaScript code is executed directly by the web browser without the need for prior compilation. This makes development and debugging easier and faster.

    history of JavaScript

    1. 1995: Created by Brendan Eich at Netscape, initially called Mocha, then renamed to LiveScript, and finally JavaScript.

    2. 1996: Microsoft creates JScript for Internet Explorer, leading to cross-browser compatibility issues.

    3. 1997: ECMA International standardizes JavaScript as ECMAScript (ES1).

    4. 2009: Major update with ECMAScript 5 (ES5) introducing new features and improvements.

    5. 2015: ECMAScript 6 (ES6) or ECMAScript 2015 brings significant enhancements (e.g., classes, modules, arrow functions).

    6. Present: Continual yearly updates to ECMAScript (e.g., ES2016, ES2017, etc.), evolving JavaScript with new features and improvements.

JavaScript has grown from a simple scripting language to a powerful tool for both client-side and server-side development.

why JavaScript is important :

  1. Web Development: Essential for creating interactive and dynamic web pages.

  2. Client-Side: Runs in the user's browser, enhancing user experience.

  3. Server-Side: Powers backend development with Node.js.

  4. Versatile: Supports multiple programming paradigms (object-oriented, functional).

  5. Integration: Works seamlessly with HTML and CSS.

  6. Rich Ecosystem: Extensive libraries and frameworks (React, Angular, Vue.js).

  7. Active Community: Large, supportive community with abundant resources.

  8. Easy to Learn: Beginner-friendly with straightforward syntax.

JavaScript is a crucial tool for modern web development, making websites interactive and responsive.

  • JavaScript interpreter:

    1. Interpreter: Runs JavaScript code directly without pre-compilation.

    2. Browser: Built into web browsers (like Chrome and Firefox).

    3. Line-by-Line: Reads and executes code one line at a time.

    4. Immediate Execution: Runs code immediately, making development quick.

    5. Debugging: Easier to test and fix errors quickly.

In essence, a JavaScript interpreter allows your code to run instantly in the browser, making it easy to create and test web applications.

  • Where to write code?

  • • In the same HTML file

  • • In a separate file, which can be embedded into HTML file.

    In HTML file

    <script type ="text/javascript>

    .............

    .................

    </script>

In External File

• External script cannot contain the <script> </script> tags!

Chapter-2 Where to write Javascript

JavaScript in HTML file

• JavaScript code must be inserted between <script> </script> tags.

• Script can be placed anywhere in HTML document (body or head) I

• <script type="text/javascript"></script>

• The type attribute is not required. JavaScript is the default scripting language in HTML

<body>
<script>
            document.write("Line1")
            </script></body>
<head>
        <script src="j1.js" > </script> </head>
document.write("JavaScript is palced in external JS file");

Where can write JS

• In head tag

• In body tag

• In external file

• In JS function (cover in later chapter)

• In event attribute's value (events will be covered in later chapter)

Chapter-3 Basics of Javascript

Javascript

• JavaScript is a programming language

• JavaScript statements are separated by semicolons.

• JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.

JS literals

In JavaScript, literals are like straightforward values that you write directly into your code. They can be numbers, strings of text, true or false values, objects, arrays, and more. Here’s a simple breakdown:

  1. Numbers: Numeric values like 42 or 3.14.

  2. Strings: Text enclosed in single (') or double (") quotes, like 'Hello!' or "JavaScript".

  3. Booleans: Values representing true or false, such as true or false.

  4. Objects: Collections of properties enclosed in curly braces {}, like { name: 'Alice', age: 30 }.

  5. Arrays: Lists of items enclosed in square brackets [], like [1, 2, 3].

  6. Null: Represents a deliberate absence of any object value, written as null.

  7. Undefined: Indicates a variable that has been declared but not assigned a value, written as undefined.

  8. Template Literals: Special strings allowing embedded expressions, enclosed by backticks (` ), like Hello, ${name}!.

These literals are the basic building blocks you use to create and work with data in JavaScript.

JS variables

• Variables are used to store data values.

•The var keyword is used to declare variables.

var x=5;

JS Operators

Operators are used to manipulate data and gives a data as result

3+4

2*5

x=5

JS Expressions

• An expression is a combination of values, variables, and operators, which computes to a value.

x=3+4*5;

y= "x="+x;

JS keywords

• var is a keyword

• As of now there are 63 keywords in JS

JS comments

• Code after double slashes // or between /* and */ is treated as a comment.

• Comments are ignored, and will not be executed

Identifier Naming Rules

• In JavaScript, the first character must be a letter, an underscore (_), or a dollar sign ($).

• Subsequent characters may be letters, digits, underscores, or dollar signs.

Variables and operators in Javascript

Variables

• JS variables are containers for storing constants

• The keyword var is used to declare variable

  • var x=4;

  • var y=3.5;

  • var z="hello";

  • var a=3+x;

    Naming rules

    • Names can contain letters, digits, underscores, and dollar sign.

    • Names must begin with a letter, $(dollar) or _ (underscore).

    • Names are case sensitive.

    Re-declaration Of Variables

    • If you re-declare a JavaScript variable, it will not lose its value.

    Re-declaration means you're trying to declare the same variable again. Whether this is allowed or not depends on the programming language you're using.

    In JavaScript, using var, you can re-declare a variable without any issues:

      var name = "Safia";
      var name = "Ali";  // No problem here
    
      let age = 25;
      let age = 30;  // This will cause an error
    
      const city = "New York";
      const city = "Los Angeles";  // This will also cause an error
    

    Concatenation Operator

    Concatenation is just a fancy word for "joining" or "putting together." When we talk about concatenation in programming, we usually mean joining strings (pieces of text) together.

    Concatenation Operator

    The concatenation operator is a symbol that tells the computer to join two or more strings together.

    • var x = "Hello" + " " + "Students";

  • • var y = "2"+4+5;

    • The concatenation operator in JavaScript is a plus (+).

      let firstName = "Safia";
      let lastName = "Ali";
      let fullName = firstName + " " + lastName;
      console.log(fullName); // Outputs: Safia Ali
    

    operator

    1. =(Assignment Operator):

      • This operator is used to assign a value to a variable.

      • Example: x = 5 means "set the value of x to 5".

    2. ==(Equal to Operator):

      • This operator is used to compare two values to see if they are equal.

      • Example: x == 5 means "check if the value of x is equal to 5".

In summary:

  • =: Think of it as "putting a value into a box". You put a value into a variable.

  • ==: Think of it as "comparing two boxes". You check if the values in the variables are the same.

    Arithmetic operators

    Arithmetic operators are used to perform basic mathematical operations. Here are the most common ones:

    1. Addition (+)

      • Adds two numbers.

      • Example: 5 + 3 equals 8.

    2. Subtraction (-)

      • Subtracts one number from another.

      • Example: 5 - 3 equals 2.

    3. Multiplication (*)

      • Multiplies two numbers.

      • Example: 5 * 3 equals 15.

    4. Division (/)

      • Divides one number by another.

      • Example: 6 / 3 equals 2.

    5. Modulus (%)

      • Gives the remainder of the division of two numbers.

      • Example: 5 % 2 equals 1 (because 5 divided by 2 is 2 with a remainder of 1).

    6. Increment (++)

      • Increases a number by 1.

      • Example:

          let a = 5;
          a++; // Now a is 6
        
    7. Decrement (--)

      • Decreases a number by 1.

      • Example:

          let a = 5;
          a--; // Now a is 4
        

Examples

Let's see how these operators work with some simple examples:

        // Addition
        let sum = 10 + 5; // sum is 15

        // Subtraction
        let difference = 10 - 5; // difference is 5

        // Multiplication
        let product = 10 * 5; // product is 50

        // Division
        let quotient = 10 / 5; // quotient is 2

        // Modulus
        let remainder = 10 % 3; // remainder is 1

        // Increment
        let a = 10;
        a++; // a is now 11

        // Decrement
        let b = 10;
        b--; // b is now 9

Summary

  • + adds numbers.

  • - subtracts numbers.

  • * multiplies numbers.

  • / divides numbers.

  • % gives the remainder of a division.

  • ++ increases a number by 1.

  • -- decreases a number by 1.

    Compound assignment operators

    Compound assignment operators in JavaScript make it easier to update the value of a variable by combining an arithmetic operation with an assignment. Instead of writing the operation and the assignment separately, you can combine them into one concise statement.

    Addition Assignment (+=)

    Explanation: Adds a value to a variable.

    • Long way:x = x + y

    • Short way:x += y

Example:

            let x = 10;
            x += 5; // Now x is 15 (10 + 5)

Subtraction Assignment (-=)

Explanation: Subtracts a value from a variable.

  • Long way:x = x - y

  • Short way:x -= y

Example:

            let x = 10;
            x -= 3; // Now x is 7 (10 - 3)

Multiplication Assignment (*=)

Explanation: Multiplies a variable by a value.

  • Long way:x = x * y

  • Short way:x *= y

Example:

            let x = 10;
            x *= 2; // Now x is 20 (10 * 2)

Division Assignment (/=)

Explanation: Divides a variable by a value.

  • Long way:x = x / y

  • Short way:x /= y

Example:

            let x = 10;
            x /= 2; // Now x is 5 (10 / 2)

Remainder Assignment (%=)

Explanation: Gets the remainder of dividing a variable by a value.

  • Long way:x = x % y

  • Short way:x %= y

Example:

            let x = 10;
            x %= 3; // Now x is 1 (10 % 3)

Exponentiation Assignment (**=)

Explanation: Raises a variable to the power of a value.

  • Long way:x = x ** y

  • Short way:x **= y

Example:

            let x = 2;
            x **= 3; // Now x is 8 (2 ** 3)

Relational operators

Relational operators in JavaScript are used to compare two values. They help you determine the relationship between those values, such as whether one is greater than, less than, equal to, or not equal to another.

  1. Greater Than (>):

    • Checks if the value on the left is greater than the value on the right.

    • Example: 5 > 3 returns true because 5 is greater than 3.

  2. Less Than (<):

    • Checks if the value on the left is less than the value on the right.

    • Example: 2 < 4 returns true because 2 is less than 4.

  3. Greater Than or Equal To (>=):

    • Checks if the value on the left is greater than or equal to the value on the right.

    • Example: 5 >= 5 returns true because 5 is equal to 5.

  4. Less Than or Equal To (<=):

    • Checks if the value on the left is less than or equal to the value on the right.

    • Example: 3 <= 4 returns true because 3 is less than 4.

  5. Equal To (==):

    • Checks if the value on the left is equal to the value on the right.

    • Example: 5 == 5 returns true because both values are the same.

    • Note: == does not consider data type, so 5 == '5' also returns true.

  6. Strictly Equal To (===):

    • Checks if the value on the left is equal to the value on the right and that they are of the same data type.

    • Example: 5 === 5 returns true, but 5 === '5' returns false because one is a number and the other is a string.

  7. Not Equal To (!=):

    • Checks if the value on the left is not equal to the value on the right.

    • Example: 5 != 3 returns true because 5 is not equal to 3.

    • Note: != does not consider data type, so 5 != '5' returns false.

  8. Strictly Not Equal To (!==):

    • Checks if the value on the left is not equal to the value on the right or if they are of different data types.

    • Example: 5 !== 3 returns true, and 5 !== '5' also returns true because they are different types.

These operators are commonly used in conditions and loops to make decisions in your code. For instance:

            let age = 18;

            if (age >= 18) {
              console.log("You are an adult.");
            } else {
              console.log("You are a minor.");
            }

In this example, the >= operator checks if age is 18 or older to determine the appropriate message to display.

Chapter-5 Control Statements

Control Statement

Control statements in programming allow you to dictate the flow of execution based on certain conditions. JavaScript, PHP, and C all share many similarities in their control statements, making it easier to transition between these languages.

1. if, if-else, and Ternary (? :) Statements

            let num = 10;

            // if statement
            if (num > 5) {
              console.log("Number is greater than 5");
            }

            // if-else statement
            if (num > 10) {
              console.log("Number is greater than 10");
            } else {
              console.log("Number is 10 or less");
            }

            or

            var age = 19;

                        if (age >=18)
                        {
                            document.write("you are eligible for vote");
                        }

                        else
                    {
                        document.write("you are not eligible for vote ");
                    }

            // ternary operator
            let result = (num > 5) ? "Greater than 5" : "5 or less";
            console.log(result);

            or

            var age=19;

                           age>=18 ? document.write("You are eligible") : document.write("you are not eligible");

2. switch Statement

              var day = 5;
                            switch (day) {
                                case 1:
                                    document.write("Sunday");

                                    break;

                                    case 2: 
                                        document.write("Monday");

                                        break;

                                        case 3:
                                            document.write("Tuesday");

                                            break;

                                        case 4:
                                            document.write("Wednesday");

                                            break;

                                            case 5:

                                                document.write("Thursday");

                                                break;

                                                case 6:

                                                    document.write("Friday");

                                                    break;

                                                    case 7:
                                                        document.write("Saturday");


                            }

3. while, do-while, and for Loops

JavaScript

            // while loop
            let count = 0;
            while (count < 5) {
              console.log(count);
              count++;
            }

            or

            var x=20,i=1;

                       while(i<=10) {

                        document.write(x + "x" + i + "=" + (x*i) + "<br/>");
                        i++;
                       }


            // do-while loop
            count = 0;
            do {
              console.log(count);
              count++;
            } while (count < 5);

            or

             var x=19,i=1;

                      do {

                        document.write(x + "x" + i + "=" + (x*i) + "<br/>");
                        i++;
                       }

                       while(i<=10);

            // for loop
            for (let i = 0; i < 5; i++) {
              console.log(i);
            }  


            var x=17;

                      for(i=1;i<10;i++){

                        document.write(x + "x" + i + "=" + (x*i) + "<br/>");

                      }

USES :

  1. while Loop : Repeat something as long as a condition is true.

  2. do-while Loop : Do something at least once, then repeat as long as a condition is true.

  3. for Loop: Repeat a task a known number of times.

    • Print numbers 1 to 5.
  4. if : Do something if a condition is true.

  5. if-else : Do something if a condition is true; otherwise, do something else.

  6. switch Statement : Do different things based on the value of a variable.

    Chapter-6 Popup Boxes

    Popup boxes in JavaScript are used to interact with the user. There are three main types of popup boxes: alert, confirm, and prompt.

    1. alert Box

    Use: Display a simple message to the user.

     // Show a popup with a message
     alert("Hello, this is an alert box!");
    
    • When this code runs, a small window (popup) appears with the message "Hello, this is an alert box!" and an OK button. The user must click OK to close the popup.

2. confirm Box

Use: Ask the user to confirm something (OK or Cancel).

                // Show a popup asking the user to confirm
                let userConfirmed = confirm("Do you want to continue?");

                if (userConfirmed) { // If the user clicked OK
                  console.log("User wants to continue.");
                } else { // If the user clicked Cancel
                  console.log("User does not want to continue.");
                }

                or

                var user = confirm ("you are continued to with red page?");
                           if (user) {
                            document.getElementsByTagName("body") [0].style.backgroundColor="red";


                           }

                           else{
                            document.write("No");
                           }
  • When this code runs, a popup appears with the message "Do you want to continue?" and two buttons: OK and Cancel. The variable userConfirmed will be true if the user clicks OK and false if the user clicks Cancel.

3. prompt Box

Use: Ask the user to input some text.

                // Show a popup asking the user to input some text
                let userName = prompt("Please enter your name:");

                if (userName !== null) { // If the user entered a name
                  console.log("Hello, " + userName + "!");
                } else { // If the user clicked Cancel
                  console.log("User did not enter a name.");
                }
  • When this code runs, a popup appears with the message "Please enter your name:" and a text input field. The variable userName will hold the text entered by the user. If the user clicks Cancel, userName will be null.

Examples Explained

  1. alert Box:

    • Use: Just to show a message.

    • Example:alert("Hello, this is an alert box!");

    • Result: Shows a popup with the message and an OK button.

  2. confirm Box:

    • Use: To ask the user to confirm something (yes or no).

    • Example:let userConfirmed = confirm("Do you want to continue?");

    • Result: Shows a popup with the message and two buttons (OK and Cancel). Stores true or false based on the user's choice.

  3. prompt Box:

    • Use: To ask the user to enter some text.

    • Example:let userName = prompt("Please enter your name:");

    • Result: Shows a popup with the message and a text input field. Stores the text entered by the user or null if the user clicks Cancel.

These popups are a simple way to interact with users and get their input.

Chapter-7 Functions

Functions in JavaScript are blocks of code designed to perform a particular task. They are executed when something invokes (calls) them.

Basic Function Syntax

A function is defined using the function keyword, followed by a name, followed by parentheses (). The code to be executed by the function is placed inside curly brackets {}.

            function sayHello() {
                console.log("Hello,Safia!");
            }

Calling a Function

After defining a function, you can call it by using its name followed by parentheses.

            sayHello();  // Output: Hello,Safia!

Functions with Parameters

You can pass data to a function using parameters. These parameters act as placeholders for the values (arguments) that you pass to the function.

            function greet(name) {
                console.log("Hello, " + name + "!");
            }

            greet("Amir");  // Output: Hello, Amir!
            greet("Safia");    // Output: Hello, Safia!

Functions with Return Values

Functions can return a value back to the caller using the return statement.

            function add(a, b) {
                return a + b;
            }

            let result = add(5, 3);  // result is 8
            console.log(result);     // Output: 8

Anonymous Functions and Function Expressions

Functions can also be defined without a name and can be stored in a variable. These are called anonymous functions.

            let sayGoodbye = function() {
                console.log("Goodbye!");
            };

            sayGoodbye();  // Output: Goodbye!

Arrow Functions

Arrow functions provide a shorter syntax for writing functions. They are especially useful for writing short functions.

             codeconst multiply = (a, b) => {
                return a * b;
            };

            console.log(multiply(4, 7));  // Output: 28

For single-line functions, you can omit the curly brackets and the return keyword.

            codeconst subtract = (a, b) => a - b;

            console.log(subtract(10, 4));  // Output: 6

Self-Invoking Functions

Functions can also be invoked automatically without being called explicitly. These are called self-invoking functions.

            code(function() {
                console.log("This is a self-invoking function!");
            })();  // Output: This is a self-invoking function!

Conclusion

Functions in JavaScript are versatile and can be used in various ways to perform different tasks. Understanding the basics of function declaration, calling, parameters, return values, and different syntaxes (such as arrow functions) will help you write efficient and clean JavaScript code.

Chapter 8 Event Handling

Event handling in JavaScript is the way JavaScript interacts with HTML elements when specific events occur. Here's a simple guide:

1. What is an Event?

An event is an action or occurrence that happens in the browser, like a user clicking a button, moving the mouse, or pressing a key.

2. Common Events:

  • click: When an element is clicked.

  • mouseover: When the mouse is moved over an element.

  • mouseout: When the mouse is moved away from an element.

  • keydown: When a key is pressed down.

  • load: When a webpage or an image has finished loading.

3. Event Handling:

Event handling is how you respond to these events. You write code that runs when an event happens.

4. Basic Steps for Event Handling:

  1. Select an element: Choose the HTML element you want to add an event to.

  2. Add an event listener: Attach an event listener to that element.

  3. Define a function: Write a function that runs when the event happens.

5. Example: Click Event

            <!DOCTYPE html>
            <html>
            <head>
                <title>Event Handling Example</title>
            </head>
            <body>
                <button id="myButton">Click Me!</button>

                <script>
                    // 1. Select the element
                    var button = document.getElementById("myButton");

                    // 2. Add an event listener
                    button.addEventListener("click", function() {
                        // 3. Define a function
                        alert("Button was clicked!");
                    });
                </script>
            </body>
            </html>

Explanation:

  • We select the button using document.getElementById("myButton").

  • We add an event listener for the click event using button.addEventListener("click", function() { ... }).

  • When the button is clicked, the function inside addEventListener runs and shows an alert saying "Button was clicked!".

6. Removing Event Listeners:

You can remove an event listener using removeEventListener.

            button.removeEventListener("click", function() {
                alert("Button was clicked!");
            });

7. Other Examples:

Mouse Over Event:

            <p id="myParagraph">Hover over me!</p>

            <script>
                var paragraph = document.getElementById("myParagraph");

                paragraph.addEventListener("mouseover", function() {
                    alert("Mouse is over the paragraph!");
                });
            </script>

Key Down Event:

            <input type="text" id="myInput" placeholder="Type something...">

            <script>
                var input = document.getElementById("myInput");

                input.addEventListener("keydown", function(event) {
                    alert("Key pressed: " + event.key);
                });
            </script>

Summary:

  • Events are actions that occur in the browser (click, mouseover, keydown, etc.).

  • Event handling means writing code that runs when these events happen.

  • Use addEventListener to attach a function to an event on an element.

  • Write the function to specify what should happen when the event occurs.