0% found this document useful (0 votes)
32 views70 pages

Introduction To HTML+CSS+Javascript& Debugging PDF

web development into

Uploaded by

Prabhat Bhusal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
32 views70 pages

Introduction To HTML+CSS+Javascript& Debugging PDF

web development into

Uploaded by

Prabhat Bhusal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 70

Introduction to web

technologies & debugging

HTML + CSS + Javascript


+ Debugging

Presented By: Prabhat Bhusal


Goals
Introduction to web technologies:

● HTML to create the document


structure and content

● CSS to control is visual aspect

● Javascript for interactivity


Anatomy of a Browser
Technologies

● HTML
● CSS
● Javascript
HTML
HTML means Hyper Text Markup Language.

The HTML allow us to define the structure of a document or a <html>


<head>
website. </head>
<body>
HTML is NOT a programming language, it’s a markup language, <div>
which means its purpose is to give structure to the content of the
website, not to define an algorithm. <p>Hi</p>

It is a series of nested tags that contain all the website information </div>
</body>
(like texts, images and videos). Here is an example of tags: </html>

<h1>This is a title</h1>
HTML: basic rules
Some rules about HTML:

● It uses XML syntax (tags with attributes, can contain other tags).
<tag_name attribute="value"> content </tag_name>
● It stores all the information that must be shown to the user.
● There are different HTML elements for different types of information and behaviour.
● The information is stored in a tree-like structure (nodes that contain nodes inside)
called DOM (Document Object Model).
● It gives the document some semantic structure (pe. this is a title, this is a section, this is
a form) which is helpful for computers to understand websites content.
● It must not contain information related to how it should be displayed (that information
belongs to the CSS), so no color information, font size, position, etc.
HTML: syntax example

<div id="main">
<!-- this is a comment -->
This is text without a tag.
<button class="mini">press me</button>
<img src="me.png" />
</div>
HTML: syntax example
Tag name
attributes

<div id="main"> comment

<!-- this is a comment --> text tag

This is text without a tag.


<button class="mini">press me</button>
<img src="me.png" /> self-closing tag
</div>
DOM is a tree

Every node can only have


one parent, and every node
can have several children,
so the structure looks like a
tree.
HTML: main tags
Although there are lots of tags in the HTML specification, 99% of the webs use a subset of
HTML tags with less that 10 tags, the most important are:

● <div>: a container, usually represents a rectangular area with information inside.


● <img/>: an image
● <a>: a clickable link to go to another URL(also called anchor tag.)
● <p>: a text paragraph
● <h1>: a title (h2,h3,h4 are titles of less importance)
● <input>: a widget to let the user introduce information
● <style> and <link>: to insert CSS rules
● <script>: to execute Javascript
● <span>: a null tag (doesn't do anything), good for tagging info
HTML: other interesting tags
There are some tags that could be useful sometimes:

● <button>: to create a button


● <forms>: to create a form to enter your details
● <section>: use to create a section of page
● <table>: to create a tables.
● <audio>: for playing audio
● <video>: to play video
● <canvas>: to draw graphics from javascript
● <iframe>: to put another website inside ours
HTML: Non Semantic tags Semantic

Semantic HTML means tag which have means


in their name.
Eg:<article>,<nav>,<header>,<footer>,
<section>

Non-Semantic HTML means tag which have


means in their name .Eg:<div>,<span>,

In conclusion there is no rule of using


semantic, its is only used for readability of
code and properly organized of tags.
HTML: wrapping the info
We use HTML tags to wrap different
information on our site.

The more structure has the information, the


easier will be to access it and present it.

We can change the way the information is


represented on the screen depending on the
tags where it is contained, so we shouldn't be
worried about using too many tags.
HTML: tagging correctly
Try to avoid doing this: Do this instead

<div> <div>
Title <h1>Title</h1>
<p>Here is content.</p>
Here is some content <p>Here is more content</p>
Here is more content </div>
</div>
HTML good use
It is good to have all the information properly wrapped in tags that give it some
semantics.

We also can extend the code semantics by adding extra attributes to the tags:

● id: tells a unique identifier for this tag


● class: tells a generic identifier for this tag

<div id="profile-picture" class="mini-image">...</div>


HTML references
HTML Reference: a description of all HTML tags.

The 25 Most used tags: a list with information of the more


common tags.

HTML5 Good practices: some tips for starters


Technologies

● HTML
● CSS
● Javascript
CSS
CSS allows us to specify how to present
(render) the document info stored in the
HTML.

Thanks to CSS we can control all the


aspects of the visualization and some other
features:
● Colors: content, background, borders
● Margins: interior margin, exterior
margin
● Position: where to put it
● Sizes: width, height
● Behaviour: changes on mouse over
CSS example
* {
color: blue; /*a comment */
margin: 10px;
font: 14px Tahoma;
}

This will change all the tags in my web ( ‘*‘ means all) to look blue with font Tahoma with
14px, and leaving a margin of 10px around.
CSS fields
Here is a list of the most common CSS fields and an example:
● color: #FF0000; red; rgba(255,00,100,1.0); //different ways to specify colors
● background-color: red;
● background-image: url('file.png');
● font: 18px 'Tahoma';
● border: 2px solid black;
● border-top: 2px solid red;
● border-radius: 2px; //to remove corners and make them more round
● margin: 10px; //distance from the border to the outer elements
● padding: 2px; //distance from the border to the inner elements
● width: 100%; 300px; 1.3em; //many different ways to specify distances
● height: 200px;
● text-align: center;
● box-shadow: 3px 3px 5px black;
● cursor: pointer;
● display: inline-block;
● overflow: hidden;
CSS how to add it
There are four ways to add CSS rules to your website:

● Inserting the code inside a style tag


<style>
p { color: blue }
</style>
● Referencing an external CSS file
<link href="style.css" rel="stylesheet" />
● Using the attribute style on a tag
<p style="color: blue; margin: 10px">
● Using Javascript (we will see this one later).
CSS selectors
Let's start by changing the background color of one tag of our website:

div {
background-color: red;
}

This CSS rule means that every tag DIV found in our website should have a red background
color. Remember that DIVs are used mostly to represent areas of our website.

We could also change the whole website background by affecting the tag body:

body {
background-color: red;
}
CSS selectors
What if we want to change one specific tag (not all the tags of the same type).

We can specify more precise selectors besides the name of the tag. For instance, by class
or id. To specify a tag with a given class name, we use the dot:

p.intro {
color: red;
}

This will affect only the tags p with class name intro:

<p class="intro">
CSS Selectors
There are several selectors we can use to narrow our rules to very specific tags of our website.

The main selectors are:

● tag name: just the name of the tag


○ p { ... } //affects to all <p> tags
● dot (.): affects to tags with that class
○ p.highlight { ... } //affects all <p> tags with class="highlight"
● sharp character (#): specifies tags with that id
○ p#intro { ... } //affects to the <p> tag with the id="intro"
● two dots (:): behaviour states (mouse on top)
○ p:hover { ... } //affects to <p> tags with the mouse over
● brackets ([attr='value']): tags with the attribute attr with the value 'value'
○ input[type="text"] {...} // affects to the input tags of the type text
CSS Selectors
You can also specify tags by its context, for example: tags that are inside of tags matching a
selector. Just separate the selectors by an space:

div#main p.intro { ... }

This will affect to the p tags of class intro that are inside the tag div of id main

<div id="main">
<p class="intro">....</p> ← Affects this one
</div>

<p class="intro">....</p> ← but not this one


CSS Selectors
And you can combine selectors to narrow it down more.

div#main.intro:hover { ... }

will apply the CSS to the any tag div with id main and class intro if the mouse is over.

And you do not need to specify a tag, you can use the class or id selectors without tag, this
means it will affect to any node of id main

#main { ... }
CSS Selectors
If you want to select only elements that are direct child of one element (not that have an
ancestor with that rule), use the > character:

ul.menu > li { ... }

Finally, if you want to use the same CSS actions to several selectors, you can use the
comma , character:

div, p { … } ← this will apply to all divs and p tags


HTML arrange
It is important to understand how the browser
arranges the elements on the screen.

Check this tutorial where it explains the


different ways an element can be arranged
on the screen.

You can change the way elements are


arranged using the display property:

div { display: inline-block; }

Also check the property float.


Box Model
It is important to note that by default any
width and height specified to an element will
not take into account its margin, so a div with
width 100px and margin 10px will measure
120px on the screen, not 100px.

This could be a problem breaking your


layout.

You can change this behaviour changing the


box model of the element so the width uses
the outmost border:

div { box-sizing: border; }


Layout
One of the hardest parts of CSS is
construing the layout of your website (the
structure inside the window) .

By default HTML tends to put everything in


one column, which is not ideal.

There has been many proposals in CSS to


address this issue (tables, fixed divs, flex,
grid, …).
Flexbox
The first big proposal to address the layout
was the flexbox model.

This model allows to arrange stuff in one


HTML
direction (vertically or horizontally) very
<div class="box">
easily. <div>One</div>
<div>Two</div>
You can even choose to arrange from right <div>Three
<br>first line
to left (reverse). <br>second line
</div>
</div>
It can also be used to arrange a series of
elements in different rows. CSS

.box {
display: flex;
}
Grid system HTML

<div class="grid-container">
Because most sites are structured in a grid, I
<div class="grid-item1">1</div>
recommend to use the CSS Grid system. <div class="grid-item2">2</div>
</div>
We just assign how many rows/columns a div
should use from the main grid and it will arrange CSS
automatically.
.grid-container {
Check this tutorial to create the site structure display: grid;
grid-template-rows: 100px 100px;
easily grid-template-columns: 100px 100px 100px;
grid-gap: 5px;
}

.grid-item1 {
background: blue;
border: black 5px solid;
grid-column-start: 1;
grid-column-end: 5;
grid-row-start: 1;
grid-row-end: 3;
}
Fullscreen divs CSS

html, body {
width: 100%;
Sometimes we want to have a div that covers height: 100%;
the whole screen (to make a webapp), }

instead of a scrolling website (more like div {


regular documents). margin: 0;
padding: 0;
}
In that case remember to use percentages to
#main {
define the size of elements, but keep in mind
width: 100%;
that percentages are relative to the element's height: 100%;
}
parent size, so you must set the size to the
<body> and <html> element to use 100%.
Trick to center

Centering divs can be hard sometimes, use this trick:


.horizontal-and-vertical-centering {
display: flex;
justify-content: center;
align-items: center;
}
CSS further reading
There are many more rules for selectors.

Check some of the links to understand them better.

One line layouts tutorials

Understanding the Box Model: a good explanation of how to position the information on your
document.

All CSS Selectors: the CSS selectors specification page.

CSS Transition: how to make animations just using CSS

TailwindCSS: a CSS Framework


Technologies

● HTML
● CSS
● Javascript
Interactivity
Once the web was already being used
they realize people wanted to interact
with the websites in a more meaningful
way.

So they added an Interpreter to execute


a script language that could modify the
content of the web dynamically.

Brendan Eich was tasked to develop it in


one week and it has become one of the
most important languages.
Javascript
A regular programming language, easy to start, hard to var my_number = 10;
master.
function say( str )
Allows to give some interactivity to the elements on the web. {
console.log( str
Syntax similar to C or Java but with no types. );
}
You can change the content of the HTML or the CSS applied
to an element. say("hello");

You can even send or retrieve information from the internet to


update the content of the web without reloading the page.
Javascript: insert code
There is three ways to execute javascript code in a website:

● Embed the code in the HTML using the <script> tag.

<script> /* some code */ </script>

● Import a Javascript file using the <script> tag:

<script src="file.js" />

● Inject the code on an event inside a tag:

<button onclick="javascript: /*code*/">press me</button>


Javascript: Syntax
Very similar to C++ or Java but much simpler.

var my_number = 10; //this is a comment


var my_string = "hello";//
console.log(“text”);//This command is to print a text.

prompt(“Enter your name”);//this is to get input from User


function say( str )
{
for(var i = 0; i < 10; ++i)
console.log(" say: " + str );
}
Javascript example
<html>
<body>
<h1>This is a title</h1>
<script>
var title = document.querySelector("h1");
title.innerHTML = "This is another title";
</script>
</body>
</html>
Javascript: Arrow Function
Arrow function is new in Javascript. It was introduced in javascript.
Easier and Convient than regular function.
// ES5
var x = function(x, y) {
return x * y;

}// ES6

const x = (x, y) => x * y;


Javascript: Asynchronous Programming
● In JavaScript, asynchronous programming means that the code does not
wait for time-consuming tasks (like loading data from a server) to complete.
Instead, it continues to execute other tasks while waiting for the long-running
operation to finish.
● Key Concepts:

❖ Callback Functions

❖ Promises

❖ Async/Await
Javascript: Asynchronous
● CallBacks
● A callback is a function passed as an argument to another function
● This technique allows a function to call another function
● A callback function can run after another function has finished.
● Code Snippet:
function fetchData(callback) {
console.log("Fetching data...");
setTimeout(() => {
callback("Data fetched successfully!");
}, 2 0 0 0 ); /. Simulate a 2 -second delay
}

fetchData((message) => {
console.log (message);
});
Javascript: Asynchronous
● Promises
● A Promise is an object that represents the eventual completion (or
failure) of an asynchronous operation. It can be in one of three
states:
• Pending: The initial state, neither fulfilled nor rejected.
• Fulfilled: The operation completed successfully, and the promise
returns a result.
• Rejected: The operation failed, and the promise returns an error.
Javascript: Promise
● Code Snippet

const fetchData = new Promise((resolve, reject) => {


setTimeout(() => {
const success = true; /. Simulate success or failure
if (success) {
resolve("Data fetched successfully!"); }
else {
reject("Error fetching data.");
}
}, 2 0 0 0 );
});
fetchData

.then((message) => console.log(message)) /. Executes if resolved


.catch((error) => console.error(error)); /. Executes if rejected
Javascript: Asynchronous
● Async and Await
● Async= makes a function return a promise
● Await= makes an async function wait for a promise.
● Async/Await is a cleaner, more readable way to handle
promises.
● Allows asynchronous code to be written in a synchronous
style, improving readability and error handling.
Javascript: Async and Await
● Code Snippet

async function fetchData(){


try{
let result = await new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched successfully!"),2 0 0 0 ;
});

console.log(result) /.Waits for the promise to resolve/.


}catch(error){
console.error(error); /.Catches any errors
}
}
fetchData();
Javascript API
Javascript comes with a rich API to do many things like:

● Access the DOM (HTML nodes)


● Do HTTP Requests
● Play videos and sounds
● Detect user actions (mouse move, key pressed)
● Launch Threads
● Access the GPU, get the Webcam image, ...

And the API keeps growing with every new update of the standard.

Check the WEB API reference to know more


Javascript: DOM
● The Document Object Model, usually referred to as
the DOM,
● is an essential part of making websites interactive.
● Is tree of nodes corresponding to HTML elements
on a page.
● Can modify, add and remove nodes on the DOM,
which will modify, add, or remove the corresponding
element on the page.
Javascript: crawling the DOM
If you want to access any element in an HTML page, you always start with accessing the
document object.
Then you can do a lot of things with the document object:
Action Example/code
Finding HTML Elements document.querySelector(CSS selector);
Changing the html elements Document.getElementbyID/classname(“id/c
lassname”).innerHTML=“new html content”;

Adding and Deleting Elements document.createElement(element);


Adding Events Handlers element.addEventListener('event',
handler);
Changing attribute Element.attribute=“new content”
Changing CSS properties Element.style.property=new Style;
Javascript: using selectors
You can retrieve elements using selectors:

var nodes = document.querySelectorAll("p.intro");

will return an array with all <p class="intro"> nodes in the web.

Or if we have already a node and we want to search inside:

var node = mynode.querySelectorAll("p.intro")


Javascript: create nodes
Create elements:
var element = document.createElement("div");

And attach them to the DOM:


document.querySelector("#main").appendChild( element );

Or remove it from its parent:


element.remove();

You can clone an element also easily:


var cloned = element.cloneNode(true);
Javascript: modify nodes
From JS you can change the attributes
mynode.id = "intro"; //sets an id
mynode.className = "important"; //set class
mynode.classList.add("good"); //to add to the current classes

Change the content


mynode.innerHTML = "<p>text to show</p>"; //change content

Modify the style (CSS)


mynode.style.color = "red"; //change any css properties

or add the behaviour of a node


mynode.addEventListener("click", function(e) {
//do something
});
Javascript: hide and show elements
Sometimes it may be useful to hide one element or show another.

You can change an element CSS directly by accessing its property style.

To avoid being displayed on the web change display to "none"

element.style.display = "none"; //hides elements from being rendered


element.style.display = ""; //displays it again
Javascript: Events
● An event handler is a JavaScript function that
runs when an event fires.
● An event listener attaches a responsive
interface to an element, which allows that
particular element to wait and “listen” for the
given event to fire.
Javascript: Working of Events
Event Listeners: In JavaScript, you can set up an event listener to listen for a specific event on an
element. When the event occurs, a function (called an event handler or callback) is executed.

Event Object: When an event occurs, the browser passes an event object to the event handler. This
object contains information about the event, such as the type of event, the target element, and any
additional data like mouse position or the key press.
Javascript: Events Types
● Mouse Events:
● Keyboard Events
● Forms Events
● Windows Events
Javascript: Events Types

● Mouse Events:
● These events are triggered by mouse actions.
● click: Fired when an element is clicked
● dblclick: Fired when an element is double-clicked.
● mouseover: Triggered when the mouse pointer moves over an element.
● Mouseout: Triggered when the mouse pointer moves out of an element.
Javascript: Events Types
Keyboard Events
● These events are triggered by mouse actions.
● keydown: Fired when a key is pressed down
● keyup: Fired when a key is released.
● keypress: Triggered when a key is pressed (deprecated in some cases in favor of keydown and keyup)
Javascript: Events Types
Forms Events
● submit: Fired when a form is submitted
● change: Fired when the value of an input element (like a text field or select box) changes.
● focus: Triggered when an element (such as an input field) gains focus.
● blur: Fired when an element loses focus.
Javascript: Events Types
Windows Events:
● load: Fired when the entire page (including its assets like images) has been loaded
● resize: Triggered when the browser window is resized.
● scroll: Fired when the user scrolls the page.
Example of a website
HTML in index.html
Javascript in code.js
<link href="style.css" rel="stylesheet"/>
<h1>Welcome</h1> //fetch the button from the DOM
<p> var button =
<button>Click me</button> document.querySelector("button");
</p>
<script src="code.js"/> //attach and event when the user clicks it
button.addEventListener("click", myfunction);

CSS in style.css //create the function that will be called


when the button is pressed
h1 { color: #333; } function myfunction()
button { {
//this shows a popup window
border: 2px solid #AAA;
alert("button clicked!");
background-color: #555; }
}
Execution flow
It is important to have a clear
understanding of the execution flow of <script>
your code. var main =
document.querySelector("#main");
Scripts are executed when the html is //main here is null, as the
being parsed. element does
//exist yet
Be careful accessing the DOM as the </script>
DOM won’t contain all until all the HTML <div id="main"></div>
is parsed. <script>
var main =
document.querySelector("#main");
//main now is the right element
</script>
Debugging
Debugging in JavaScript refers to the process
of identifying and fixing errors or bugs in code.

It involves using various tools like browser


consoles, debuggers, and logging techniques to
analyze runtime behavior, trace program flow,
and resolve issues efficiently.

Using console.log() for debugging in JavaScript


involves strategically placing logging statements
throughout the code to output variable values,
object properties, or custom messages to the
console.
Debugging
Press Control + Shift + I (or F12) to open DevTools
Debugging
To debug the the website we can use the developer tools in
any browser.

Taking example in the perspective of

Chrome.

● Right click on mouse and click on inspect Element.


● Go to the "Elements" tab (Chrome/Firefox/Edge)
● Open the "Console" tab to view logs, errors, and run
JavaScript commands.
Exercise
● Create the layout and code for Traverse
● Structured like:
● Main container

○ Messages area

■ message

○ Typing area area

■ input
Exercise
● Create the layout and code for Traverse
● Structured like:
● Main container

○ Messages area

■ message

○ Typing area area

■ input
Console.log(“Thank
You”);
Alert(“any
queries”);

You might also like