Movatterモバイル変換


[0]ホーム

URL:


PPTX, PDF100 views

Java script and html new

HTML defines the structure and layout of a web page. It uses elements like <h1> for headings and <p> for paragraphs to structure content. CSS can be used to style HTML elements by specifying properties for things like color, font, size, and layout. JavaScript can dynamically update HTML content and attributes, adding interactivity to web pages. It is one of the core languages all web developers must learn along with HTML and CSS.

Embed presentation

Download to read offline
Java Script and HTML
HTML• HTML stands for Hyper Text Markup Language• HTML describes the structure of a Web page• HTML consists of a series of elements• HTML elements tell the browser how to display the content• HTML elements are represented by tags• HTML tags label pieces of content such as "heading", "paragraph", "table", and soon• Browsers do not display the HTML tags, but use them to render the content ofthe page• What is Website, WebPage and Internet
Use of html• First developed by Tim Berners-Lee in 1990, HTML is short forHyperText Markup Language. HTML is used to create electronicdocuments (called pages) that are displayed on the World Wide Web.Each page contains a series of connections to other pages calledhyperlinks.
First HTML PAGE• <!DOCTYPE html><html><head><title>Page Title</title></head><body><h1>This is a Heading</h1><p>This is a paragraph.</p></body></html>
HTML Document•The <!DOCTYPE html> declaration defines this document tobe HTML5•The <html> element is the root element of an HTML page•The <head> element contains meta information about thedocument•The <title> element specifies a title for the document•The <body> element contains the visible page content•The <h1> element defines a large heading•The <p> element defines a paragraph
HTML TagsHTML TagsHTML tags are element names surrounded by angle brackets:<tagname>content goes here...</tagname>•HTML tags normally come in pairs like <p> and </p>•The first tag in a pair is the start tag, the second tag is the end tag•The end tag is written like the start tag, but with a forward slash inserted before thetag name
HTML HeadingsHTML headings are defined with the <h1> to <h6> tags.<h1> defines the most important heading.<h6> defines the least important heading:Example<h1>This is heading 1</h1><h2>This is heading 2</h2><h3>This is heading 3</h3>
HTML ParagraphsHTML paragraphs are defined with the <p> tag:Example<p>This is a paragraph.</p><p>This is another paragraph.</p>
HTML LinksHTML links are defined with the <a> tag:Example<a href="https://www.w3schools.com">This is a link</a>
HTML ImagesHTML images are defined with the <img> tag.The source file (src), alternative text (alt), width, and heightare provided as attributes:Example<img src=“day01.jpg" alt="W3Schools.com" width="104" height="142">
Create HTML Document• Till now
HTML Active ControlsHTML ButtonsHTML buttons are defined with the <button> tag:Example<button>Click me</button>
HTML ListsHTML lists are defined with the <ul> (unordered/bullet list) or the <ol> (ordered/numberedlist) tag, followed by <li> tags (list items):Example<ul><li>Coffee</li><li>Tea</li><li>Milk</li></ul><ol><li>Coffee</li><li>Tea</li><li>Milk</li>
Empty HTML ElementsHTML elements with no content are called emptyelements.<br> is an empty element without a closing tag (the<br> tag defines a line break):Example<p>This is a <br> paragraph with a linebreak.</p>
HTML Attributes• All HTML elements can have attributes• Attributes provide additional information about an element• Attributes are always specified in the start tag• Attributes usually come in name/value pairs like: name="value“• <a href="https://www.w3schools.com">This is a link</a>• <img src="img_girl.jpg" width="500" height="600">• <p style="color:red">This is a paragraph.</p>• <p title="I'm a tooltip">This is a paragraph.</p>• <p title='John "ShotGun" Nelson'>
Create HTML• Till now
The HTML Style AttributeSetting the style of an HTML element, can be done with thestyle attribute.The HTML style attribute has the following syntax:<tagname style="property:value;">The property is a CSS property. The value is a CSS value.
Background ColorThe CSS background-color property defines the background colorfor an HTML element.This example sets the background color for a page to powderblue:Example<body style="background-color:powderblue;"><h1>This is a heading</h1><p>This is a paragraph.</p></body>
Text ColorThe CSS color property defines the text color for an HTML element:Example<h1 style="color:blue;">This is a heading</h1><p style="color:red;">This is a paragraph.</p>
Text SizeThe CSS font-size property defines the text size for an HTMLelement:Example<h1 style="font-size:300%;">This is a heading</h1><p style="font-size:160%;">This is a paragraph.</p>
Text AlignmentThe CSS text-align property defines the horizontal textalignment for an HTML element:Example<h1 style="text-align:center;">Centered Heading</h1><p style="text-align:center;">Centered paragraph.</p>
In the previous chapter, you learned about the HTML style attribute.HTML also defines special elements for defining text with a special meaning.HTML uses elements like <b> and <i> for formatting output, like bold or italic text.Formatting elements were designed to display special types of text:•<b> - Bold text•<strong> - Important text•<i> - Italic text•<em> - Emphasized text•<mark> - Marked text•<small> - Small text•<del> - Deleted text•<ins> - Inserted text•<sub> - Subscript text•<sup> - Superscript text
Quotes, Abbr and Address• <p>Here is a quote from WWF's website:</p><blockquote cite="http://www.worldwildlife.org/who/index.html">For 50 years, WWF has been protecting the future of nature. The world's leading conservation organization, WWFworks in 100 countries and is supported by 1.2 million members in the United States and close to 5 million globally.</blockquote>• Abbreviation• <p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p>• Address• <address>Written by John Doe.<br>Visit us at:<br>Example.com<br>Box 564, Disneyland<br>USA</address>
Create HTML• Till now
HTML Colors
Background / Foreground Color•Example•<h1 style="background-color:DodgerBlue;">HelloWorld</h1><p style="background-color:Tomato;">Lorem ipsum...</p>•Text Color• <h1 style="color:Tomato;">Hello World</h1><p style="color:DodgerBlue;">Lorem ipsum...</p><p style="color:MediumSeaGreen;">Ut wisi enim...</p>
Border Color• You can set the color of borders:• Hello World• Hello World• Hello World• Example• <h1 style="border:2px solid Tomato;">Hello World</h1><h1 style="border:2px solid DodgerBlue;">Hello World</h1><h1 style="border:2px solid Violet;">Hello World</h1>
HyperLinks• HTML links are hyperlinks.• You can click on a link and jump to another document.• When you move the mouse over a link, the mouse arrow will turninto a little hand.• Note: A link does not have to be text. It can be an image or any otherHTML element.• <a href="url">link text</a>• <a href="html_images.asp">HTML Images</a>
Styles, StyleSheets, CSS
Styling HTML with CSSCSS stands for Cascading Style Sheets.CSS describes how HTML elements are to be displayed on screen,paper, or in other media.CSS saves a lot of work. It can control the layout of multiple webpages all at once.CSS can be added to HTML elements in 3 ways:•Inline - by using the style attribute in HTML elements•Internal - by using a <style> element in the <head> section•External - by using an external CSS file
Inline CSSAn inline CSS is used to apply a unique style to a single HTML element.An inline CSS uses the style attribute of an HTML element.This example sets the text color of the <h1> element to blue:Example<h1 style="color:blue;">This is a Blue Heading</h1>
Internal CSSAn internal CSS is used to define a style for a single HTML page.An internal CSS is defined in the <head> section of an HTML page, within a <style> element:Example<!DOCTYPE html><html><head><style>body {background-color: powderblue;}h1 {color: blue;}p {color: red;}</style></head><body><h1>This is a heading</h1> <p>This is a paragraph.</p></body></html>
External CSSAn external style sheet is used to define the style for many HTML pages.With an external style sheet, you can change the look of an entire web site, bychanging one file!To use an external style sheet, add a link to it in the <head> section of the HTML page:<!DOCTYPE html><html><head><link rel="stylesheet" href="styles.css"></head><body><h1>This is a heading</h1><p>This is a paragraph.</p></body>
StyleSheet Attributes•Use the HTML style attribute for inline styling•Use the HTML <style> element to define internal CSS•Use the HTML <link> element to refer to an external CSS file•Use the HTML <head> element to store <style> and <link> elements•Use the CSS color property for text colors•Use the CSS font-family property for text fonts•Use the CSS font-size property for text sizes•Use the CSS border property for borders•Use the CSS padding property for space inside the border•Use the CSS margin property for space outside the border
• <style>a:link {color: green; background-color: transparent; text-decoration: none;}a:visited {color: pink; background-color: transparent; text-decoration: none;}a:hover {color: red; background-color: transparent; text-decoration: underline;}a:active {color: yellow;background-color: transparent;text-decoration: underline;}Style for Hyperlink
HTML Links - The target AttributeThe target attribute specifies where to open the linked document.The target attribute can have one of the following values:•_blank - Opens the linked document in a new window or tab•_self - Opens the linked document in the same window/tab as itwas clicked (this is default)•_parent - Opens the linked document in the parent frame•_top - Opens the linked document in the full body of the window•framename - Opens the linked document in a named frame<a href="https://www.w3schools.com/" target="_blank">Visit W3Schools!</a>
Create HTML• Till now
HTML Images• <!DOCTYPE html><html><head><style>img {width: 100%;}</style></head><body><img src="html5.gif" alt="HTML5 Icon" width="128" height="128"><img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;"></body></html>The width, height, and style attributes are valid in HTML.However, we suggest using the style attribute. It prevents styles sheets from changing the size of images:
Image MapsThe <map> tag defines an image-map. An image-map is an image with clickable areas.In the image below, click on the computer, the phone, or the cup of coffee:<img src="workplace.jpg" alt="Workplace" usemap="#workmap"><map name="workmap"><area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm"><area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm"><area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm"></map>
Section 02Tables (HTML)JavaScript
TableCompany Contact CountryAlfreds Futterkiste Maria Anders GermanyCentro comercial Moctezuma Francisco Chang MexicoErnst Handel Roland Mendel AustriaIsland Trading Helen Bennett UKLaughing Bacchus Winecellars Yoshi Tannamuri CanadaMagazzini Alimentari Riuniti Giovanni Rovelli Italy
Example• <table style="width:100%"><tr><th>Firstname</th> <th>Lastname</th><th>Age</th></tr><tr><td>Jill</td> <td>Smith</td> <td>50</td></tr><tr><td>Eve</td> <td>Jackson</td> <td>94</td></tr></table>
HTML Table - Adding a BorderIf you do not specify a border for the table, it will be displayedwithout borders.A border is set using the CSS border property:Exampletable, th, td {border: 1px solid black;}table, th, td {border: 1px solid black;border-collapse: collapse;}
HTML Table - Left-align HeadingsBy default, table headings are bold and centered.To left-align the table headings, use the CSS text-align propExampleth {text-align: left;}
HTML Table - Cells that Span Many ColumnsTo make a cell span more than one column, use the colspan attribute:Example<table style="width:100%"><tr><th>Name</th><th colspan="2">Telephone</th></tr><tr><td>Bill Gates</td><td>55577854</td><td>55577855</td></tr></table>
HTML Table - Cells that Span Many RowsTo make a cell span more than one row, use the rowspan attribute:Example<table style="width:100%"><tr><th>Name:</th><td>Bill Gates</td></tr><tr><th rowspan="2">Telephone:</th><td>55577854</td></tr><tr><td>55577855</td></tr></table>
HTML Table - Adding a CaptionTo add a caption to a table, use the <caption> tag:Example<table style="width:100%"><caption>Monthly savings</caption><tr><th>Month</th> <th>Savings</th></tr><tr><td>January</td> <td>$100</td></tr><tr><td>February</td> <td>$50</td></tr>
javaScript• Why Study JavaScript?• JavaScript is one of the 3 languages all web developers must learn:• 1. HTML to define the content of web pages• 2. CSS to specify the layout of web pages• 3. JavaScript to program the behavior of web pages
First JavaScript• <!DOCTYPE html>• <html>• <body>• <h2>JavaScript in Body</h2>• <p id="demo"></p>• <script>• document.getElementById("demo").innerHTML = "MyFirst JavaScript";• </script>• </body>
JavaScript Function• <!DOCTYPE html><html><head><script>function myFunction() {document.getElementById("demo").innerHTML = "Paragraph changed.";}</script></head><body>• <h1>A Web Page</h1><p id="demo">A Paragraph</p><button type="button" onclick="myFunction()">Try it</button>• </body></html>
JavaScript Can Change HTML ContentOne of many JavaScript HTML methods is getElementById().This example uses the method to "find" an HTML element (withid="demo") and changes the element content (innerHTML) to"Hello JavaScript":<!DOCTYPE html><html><body><h2>What Can JavaScript Do?</h2><p id="demo">JavaScript can change HTML content.</p><button type="button"onclick='document.getElementById("demo").innerHTML = "HelloJavaScript!"'>Click Me!</button></body></html>
Light bulb• <!DOCTYPE html>• <html>• <body>• <h2>What Can JavaScript Do?</h2>• <p>JavaScript can change HTML attribute values.</p>• <p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>• <button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>• <img id="myImage" src="pic_bulboff.gif" style="width:100px">• <button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>• </body>• </html>
Changing html cstyle• <!DOCTYPE html>• <html>• <body>• <h2>What Can JavaScript Do?</h2>• <p id="demo">JavaScript can change the style of an HTML element.</p>• <button type="button"onclick="document.getElementById('demo').style.fontSize='35px'">ClickMe!</button>• </body>• </html>
Hiding html content• <!DOCTYPE html>• <html>• <body>• <h2>What Can JavaScript Do?</h2>• <p id="demo">JavaScript can hide HTML elements.</p>• <button type="button"onclick="document.getElementById('demo').style.display='none'">ClickMe!</button>• </body>• </html>
External Call of JavaScriptExternal scripts are practical when the same code is used in many different web pages.JavaScript files have the file extension .js.To use an external script, put the name of the script file in the src (source) attribute ofa <script> tag:Example<script src="myScript.js"></script>Try it Yourself »You can place an external script reference in <head> or <body> as you like.The script will behave as if it was located exactly where the <script> tag is located.External scripts cannot contain <script> tags.
CODE• <!DOCTYPE html>• <html>• <body>• <h2>External JavaScript</h2>• <p id="demo">A Paragraph.</p>• <button type="button"onclick="myFunction()">Try it</button>• <p>(myFunction is stored in an external filecalled "myScript.js")</p>• <script src="Script1.js"></script>• </body>// JavaScript source codefunction myFunction() {document.getElementById("demo").innerHTML = "I am called from external file";}
External JavaScript Advantages• Placing scripts in external files has some advantages:• It separates HTML and code• It makes HTML and JavaScript easier to read and maintain• Cached JavaScript files can speed up page loads• To add several script files to one page - use several script tags:
JavaScript Display PossibilitiesJavaScript can "display" data in different ways:•Writing into an HTML element, using innerHTML.•Writing into the HTML output using document.write()•Writing into an alert box, using window.alert().•Writing into the browser console, using console.log(
1. Using innerHTMLTo access an HTML element, JavaScript can use the document.getElementById(id) method.The id attribute defines the HTML element. The innerHTML property defines the HTML content:Example<!DOCTYPE html><html><body><h1>My First Web Page</h1><p>My First Paragraph</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = 5 + 6;</script></body></html>
2. Document write• <!DOCTYPE html><html><body><h1>My First Web Page</h1><p>My first paragraph.</p><script>document.write(5 + 6);</script></body></html>
3. window.alert()• <!DOCTYPE html><html><body><h1>My First Web Page</h1><p>My first paragraph.</p><script>window.alert(5 + 6);</script></body></html>
Semicolons ;• Semicolons separate JavaScript statements.• Add a semicolon at the end of each executablestatement:• var a, b, c; // Declare 3 variablesa = 5; // Assign the value 5 to ab = 6; // Assign the value 6 to bc = a + b; // Assign the sum of a and b to c• When separated by semicolons, multiple statements onone line are allowed:• a = 5; b = 6; c = a + b;
• <!DOCTYPE html>• <html>• <body>• <h2>JavaScript Statements</h2>• <p>Multiple statements on one line is allowed.</p>• <p id="demo1"></p>• <script>• var a, b, c;• a = 5; b = 6; c = a + b;• document.getElementById("demo1").innerHTML = c;• </script></body>• </html>
Code blocks• <!DOCTYPE html>• <html>• <body>• <h2>JavaScript Statements</h2>• <p>JavaScript code blocks are written between { and }</p>• <button type="button" onclick="myFunction()">Click Me!</button>• <p id="demo1"></p> <p id="demo2"></p>• <script>• function myFunction() {• document.getElementById("demo1").innerHTML = "Hello COMSATS!";• document.getElementById("demo2").innerHTML = “How are all?";• }• </script></body>• </html>
Keyword Descriptionbreak Terminates a switch or a loopcontinue Jumps out of a loop and starts at the topdebugger Stops the execution of JavaScript, and calls (ifavailable) the debugging functiondo ... while Executes a block of statements, and repeats theblock, while a condition is truefor Marks a block of statements to be executed, aslong as a condition is truefunction Declares a functionif ... else Marks a block of statements to be executed,depending on a conditionreturn Exits a functionswitch Marks a block of statements to be executed,depending on different casestry ... catch Implements error handling to a block ofstatementsvar Declares a variable
JS Strings• <html> <body>• <h2>JavaScript Strings</h2>• <p>You can use quotes inside a string, as long as they don't match the quotessurrounding the string.</p>• <p id="demo"></p>• <script>• var answer1 = "It's alright";• var answer2 = "He is called 'Johnny'";• var answer3 = 'He is called "Johnny"';• document.getElementById("demo").innerHTML =• answer1 + "<br>" + answer2 + "<br>" + answer3;• document.getElementById("demo").innerHTML = "<br>" + "String length is " +answer3.length;• </script></body> </html>
Special CharactersThe string will be chopped to "We are the so-called ".The solution to avoid this problem, is to use the backslash escape character.The backslash () escape character turns special characters into string characters:Code Result Description' ' Single quote" " Double quote  Backslash<body><h2>JavaScript Strings</h2><p>The escape sequence " inserts a double quote in a string.</p><p id="demo"></p><script>var x = "We are the so-called "Vikings" from the north.";document.getElementById("demo").innerHTML = x;</script></body>
Strings Can be ObjectsNormally, JavaScript strings are primitive values, created from literals:var firstName = “xyz";But strings can also be defined as objects with the keyword new:var firstName = new String(“xyz");Examplevar x = “xyz";var y = new String(“xyz");// typeof x ??// typeof y ??
String MethodsFinding a String in a StringThe indexOf() method returns the index of (the position of) the first occurrenceof a specified text in a string:Examplevar str = "Please locate where 'locate' occurs!";var pos = str.indexOf("locate");Searching for a String in a StringThe search() method searches a string for a specified value and returns the positionof the match:Examplevar str = "Please locate where 'locate' occurs!";var pos = str.search("locate");Extracting String PartsThere are 3 methods for extracting a part of a string:•slice(start, end)•substring(start, end)•substr(start, length)•Replace (“old text”,”new text”)
String Methods• String.toUpperCase() and String.toLowerCase()• String.Concat() or use + Operator• String.trim()• String.charAt(SomeIndex)• String.charCodeAt(someindex) returns ASCII Code• String[index] or String[index] = ‘x’• Split ()• var txt = "a,b,c,d,e"; // Stringtxt.split(","); // Split on commastxt.split(" "); // Split on spacestxt.split("|");
JS Arrays<!DOCTYPE html><html><body><h2>JavaScript Arrays</h2><p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p><p id="demo"></p><script>var cars = ["Saab", "Volvo", "BMW"];cars[0] = "Opel";document.getElementById("demo").innerHTML = cars;</script></body></html>
Array Elements Can Be Objects• JavaScript variables can be objects. Arrays are specialkinds of objects.• Because of this, you can have variables of different typesin the same Array.• You can have objects in an Array. You can have functionsin an Array. You can have arrays in an Array:• myArray[0] = Date.now;myArray[1] = myFunction;myArray[2] = myCars;Array Properties and MethodsThe real strength of JavaScript arrays are thebuilt-in array properties and methods:Examplesvar x = cars.length; // The length propertyreturns the number of elementsvar y = cars.sort(); // The sort() methodsorts arrays
Looping through Arrays• <body>• <h2>JavaScript Arrays</h2>• <p>The best way to loop through an array is using a standard for loop:</p>• <p id="demo"></p>• <script>• var fruits, text, fLen, i;• fruits = ["Banana", "Orange", "Apple", "Mango"];• fruits.push("Lemon"); fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits• fLen = fruits.length;• text = "<ul>";• for (i = 0; i < fLen; i++) {• text += "<li>" + fruits[i] + "</li>"; }• text += "</ul>";• document.getElementById("demo").innerHTML = text;• </script>• </body>
Sorting Arrays• <body>• <h2>JavaScript Array Sort</h2>• <p>Click the buttons to sort the array alphabetically or numerically.</p>• <button onclick="myFunction1()">Sort Alphabetically</button>• <button onclick="myFunction2()">Sort Numerically</button>• <p id="demo"></p>• <script>• var points = [40, 100, 1, 5, 25, 10];• document.getElementById("demo").innerHTML = points;• function myFunction1() {• points.sort();• document.getElementById("demo").innerHTML = points; }• function myFunction2() {• points.sort(function (a, b) { return a - b });• document.getElementById("demo").innerHTML = points;• } </script> </body>
JS DatesDate objects are created with the new Date() constructor.There are 4 ways to create a new date object:new Date()new Date(year, month, day, hours, minutes, seconds, millnew Date(milliseconds)new Date(date string)
Date methodsMethod DescriptiongetFullYear() Get the year as a four digit number (yyyy)getMonth() Get the month as a number (0-11)getDate() Get the day as a number (1-31)getHours() Get the hour (0-23)getMinutes() Get the minute (0-59)getSeconds() Get the second (0-59)getMilliseconds() Get the millisecond (0-999)getTime() Get the time (milliseconds since January 1,1970)getDay() Get the weekday as a number (0-6)Date.now() Get the time. ECMAScript 5.
Date methods<!DOCTYPE html><html><body><h2>JavaScript getMonth()</h2><p>The getMonth() method returns the month as a number:</p><p>You can use an array to display the name of the month:</p><p id="demo"></p><script>var d = new Date();var months =["January","February","March","April","May","June","July","August","September","October","November","December"];document.getElementById("demo").innerHTML = months[d.getMonth()];</script></body></html>
JavaScript Form Validation• HTML form validation can be done by JavaScript.• If a form field (fname) is empty, this function alerts a message, and returns false,to prevent the form from being submitted:• JavaScript Example• function validateForm() {var x = document.forms["myForm"]["fname"].value;if (x == "") {alert("Name must be filled out");return false;}}
Number Validation• <script>• function myFunction() {• var x, text;• // Get the value of the input field with id="numb"• x = document.getElementById("numb").value;• // If x is Not a Number or less than one or greater than 10• if (isNaN(x) || x < 1 || x > 10) {• text = "Input not valid";• } else {• text = "Input OK";• } document.getElementById("demo").innerHTML = text;• }• </script>
Constraint Validation HTML Input AttributesAttribute Descriptiondisabled Specifies that the input element should be disabledmax Specifies the maximum value of an input elementmin Specifies the minimum value of an input elementpattern Specifies the value pattern of an input elementrequired Specifies that the input field requires an elementtype Specifies the type of an input element
Constraint Validation DOM• If an input field contains invalid data, display a message:• The checkValidity() Method• <input id="id1" type="number" min="100" max="300" required><button onclick="myFunction()">OK</button><p id="demo"></p><script>function myFunction() {var inpObj = document.getElementById("id1");if (!inpObj.checkValidity()) {document.getElementById("demo").innerHTML = inpObj.validationMessage;}}</script>Property DescriptioncheckValidity() Returns true if an input element contains valid data.setCustomValidity() Sets the validationMessage property of an input element.
JavaScript EventsThere are a lot of different types of events that can occur, for example:• The user clicking the mouse over a certain element or hovering the cursor over acertain element.• The user pressing a key on the keyboard.• The user resizing or closing the browser window.• A web page finishing loading.• A form being submitted.• A video being played, or paused, or finishing play.• An error occurring.You can gather from this (and from glancing at the MDN Event reference) that thereare a lot of events that can be responded to.Each available event has an event handler, which is a block of code (usually a JavaScriptfunction that you as a programmer create) that will be run when the event fires.
JavaScript HTML EventsEvent Descriptiononchange An HTML element has been changedonclick The user clicks an HTML elementonmouseover The user moves the mouse over an HTMLelementonmouseout The user moves the mouse away from anHTML elementonkeydown The user pushes a keyboard keyonload The browser has finished loading the page
What can JavaScript Do?Event handlers can be used to handle, and verify, user input, user actions, and browser actions:• Things that should be done every time a page loads• Things that should be done when the page is closed• Action that should be performed when a user clicks a button• Content that should be verified when a user inputs data• And more ...Many different methods can be used to let JavaScript work with events:• HTML event attributes can execute JavaScript code directly• HTML event attributes can call JavaScript functions• You can assign your own event handler functions to HTML elements• You can prevent events from being sent or being handled• And more ...
Button Event<html><head><title> JavaScript Button Event Query Selector </title></head><body><button>Change color</button><script>const btn = document.querySelector('button');function random(number) { return Math.floor(Math.random() * (number+1)); }btn.onclick = function() {const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';document.body.style.backgroundColor = rndCol;}</script></body></html>
Events in JavaScript• Node.js is a very popular JavaScript runtime that enables developers to useJavaScript to build network and server-side applications.• The Node.js event model relies on listeners to listen for events and emitters to emitevents periodically — it doesn't sound that different, but the code is quite different,making use of functions like on() to register an event listener, and once() to registeran event listener that unregisters after it has run once. The HTTP connect event docsprovide a good example of use.• As another example, you can also use JavaScript to build cross-browseradd-ons — browser functionality enhancements —• using a technology called WebExtensions. The event model is similar to the webevents model, but a bit different — event listeners properties are camel-cased (suchas onMessage rather than onmessage), and need to be combined with theaddListener function. See the runtime.onMessage page for an example.
How to Program an Event in Jscriptconst btn = document.querySelector('button'); btn.onclick = function() { const rndCol = 'rgb(' + random(255) +',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; }1. Use OnClick PropertyThe onclick property is the event handler property being used in this situation. It is essentially a property like anyother available on the button (e.g. btn.textContent, or btn.style), but it is a special type — when you set it to be equalto some code, that code is run when the event fires on the button.const btn = document.querySelector('button'); function bgChange() { const rndCol = 'rgb(' +random(255) + ',' + random(255) + ',' + random(255) + ')';document.body.style.backgroundColor = rndCol; }btn.onclick = bgChange;2. Use Event Handler using Named Function
Practice: Other Event Handlersmake a local copy of Button_Event_Query_Selector,and open it in your browser. Now try changing btn.onclick to the following different values in turn, andobserving the results in the example:•btn.onfocus and btn.onblur — The color changes when the button is focused and unfocused; try pressing tab to focuson the button and press tab again to focus away from the button. These are often used to display information abouthow to fill in form fields when they are focused, or display an error message if a form field has just been filled in withan incorrect value.•btn.ondblclick — The color changes only when the button is double-clicked.•window.onkeypress, window.onkeydown, window.onkeyup — The color changes when a key is pressed on the keyboard.The keypress event refers to a general press (button down and then up), while keydown and keyup refer to just the keydown and key up parts of the keystroke, respectively. Note that it doesn't work if you try to register this eventhandler on the button itself — we've had to register it on the window object, which represents the entire browserwindow.•btn.onmouseover and btn.onmouseout — The color changes when the mouse pointer is moved so it begins hovering overthe button, or when pointer stops hovering over the button and moves off of it, respectively.
+Note: Some events are very general and available nearly anywhere (forexample an onclick handler can be registered on nearly any element),whereas some are more specific and only useful in certain situations(for example it makes sense to use onplay only on specific elements,such as <video>).<button onclick="alert('Hello, this is my old-fashioned event handler!');">Pressme</button>
Inline Events<html><head><meta charset="utf-8"><title>Random color example — event handler attribute</title><style>button {margin: 10px};</style></head><body><button onclick="bgChange()">Change color</button><script>function random(number) {return Math.floor(Math.random()*number);}function bgChange() {const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';document.body.style.backgroundColor = rndCol;}</script></body></html>
Event Coding GuideYou can find HTML attribute equivalents for many of the event handler properties;however, you shouldn't use these — they are considered bad practice. It mightseem easy to use an event handler attribute if you are just doing something reallyquick, but they very quickly become unmanageable and inefficient.For a start, it is not a good idea to mix up your HTML and your JavaScript, as itbecomes hard to parse — keeping your JavaScript all in one place is better; if it is ina separate file you can apply it to multiple HTML documents.One button is OK, but what if you had 100 buttons? You'd have to add 100attributes to the file; it would very quickly turn into a maintenance nightmare. WithJavaScript, you could easily add an event handler function to all the buttons on thepage no matter how many there were, using something like this
JavaScript HTML DOM Events
The newest type of event mechanism is defined in the Document Object Model (DOM) Level 2 EventsSpecification, which provides browsers with a new function — addEventListener(). This functions in a similarway to the event handler properties, but the syntax is obviously different.addEventListener() andremoveEventListener()const btn = document.querySelector('button');function bgChange() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) +')';document.body.style.backgroundColor = rndCol; }btn.addEventListener('click', bgChange);Add_Event_Lister_HTMLInside the addEventListener() function, we specify two parameters — the name of the event we want to register thishandler for, and the code that comprises the handler function we want to run in response to it. Note that it is perfectlyappropriate to put all the code inside the addEventListener()btn.removeEventListener('click', bgChange);
EventListener Advantages• for larger, more complex programs it can improve efficiency to clean upold unused event handlers.• this allows you to have the same button performing different actions indifferent circumstances — all you have to do is add or remove eventhandlers as appropriate.• Second, you can also register multiple handlers for the same listener. Thefollowing two handlers wouldn't both be applied:myElement.onclick = functionA;myElement.onclick = functionB;The second line overwrites the value of onclick set by the first line. This would work, however:myElement.addEventListener('click', functionA);myElement.addEventListener('click', functionB);using DOM Listeners both functions will work on click
Event Objects• Sometimes inside an event handler function, you might see aparameter specified with a name such as event, evt, or simply e. This iscalled the event object, and it is automatically passed to event handlersto provide extra features and information. For example, let's rewriteour random color example again slightly:function bgChange(e) { const rndCol = 'rgb(' + random(255) + ',' + random(255) +',' + random(255) + ')';e.target.style.backgroundColor = rndCol; console.log(e); }btn.addEventListener('click', bgChange);an event object, e, in the function, and in the function setting a background color style on e.target — whichis the button itself. The target property of the event object is always a reference to the element that theevent has just occurred upon. So in this example, we are setting a random background color on the button,not the page. Example
JS Animation• D yourself
JavaScript Examples• JavaScript PopoUP• JavaScript Matrix• JavaScript Form
JavaScript vs React.JS• Web apps are becoming increasingly complex and dynamic. Inresponse, new tools and libraries like React have been created tospeed up the process.• But how is developing a web app with React different than developingan app with just plain JavaScript?
JavaScript• To set some boundaries, let’s first define what we mean by "plain"JavaScript (also called "vanilla" JavaScript).• React is a library that defines the way apps are written. It does this bysetting very clear rules about how data can flow through the app, andhow the UI will adapt as a result of that changing data. There areother libraries that set similar boundaries, such as Angular and Vue.• Plain JavaScript (that is, JavaScript written without libraries) on theother hand, doesn’t set any rules about how data can be defined, orhow the UI can be changed. That makes apps written without theselibraries more freeform and customizable. But going this route canalso lead to problems down the road
The major differencesSince there are so many ways to write vanilla JS, it can be difficult to pindown a list of differences that applies to 100% of apps. But here we’lldefine some key differences that apply to many plain JS apps that arewritten without a framework.• How the user interface is first created• How functionality is split up across the app• How data is stored on the browser• How the UI is updated
In plain JS, the initial user interface is generally created in HTMLon the server. Meaning,HTML is dynamically created on the server, and might looksomething like this:<div><h1>Grocery List</h1><ul><li>Milk</li><li>Bread</li><li>Eggs</li></ul></div>That gets sent to the web browser and displayed—no JavaScript needed yet!In contrast, a React app will start with a fixed HTML file that looks like this:<div id=“root”></div>How the user interface is first created
UI in REACTInstead of defining the initial UI on the server, the UI gets defined on the browser. So the app starts with a blankcontainer (a div in this case), and then the UI gets loaded into that container.The UI is defined by a component that returns JSX. JSX looks like HTML, but is actually JavaScript - and might looklike this:function GroceryList(props) {return (<div><h1>Grocery List</h1><ul><li>Milk</li><li>Bread</li><li>Eggs</li></ul></div>)};
• The UI is defined by a component that returns JSX. JSX looks like HTML, but isactually JavaScript - and might look like this:function GroceryList(props) {return (<div><h1>Grocery List</h1><ul><li>Milk</li><li>Bread</li><li>Eggs</li></ul></div>)};

Recommended

PPTX
Introduction to HTML
PDF
Web development using html 5
PPT
Html introduction
KEY
Html intro
PPTX
Web Development Using CSS3
PDF
Web Development Using CSS3
DOC
Css introduction
PPTX
Web Page Designing Using HTML
PDF
Introduction to Html by Ankitkumar Singh
PDF
What is HTML - An Introduction to HTML (Hypertext Markup Language)
PPTX
PPTX
Html
PPTX
HTML Basics 1 workshop
PPTX
HTML, CSS, JavaScript for beginners
PDF
HTML Lecture Part 1 of 2
PDF
Intro to HTML and CSS basics
PPT
Lecture1and2
PPTX
Css module1
PPTX
PPTX
Html 5
PPTX
PPTX
Unit 1wt
PPTX
Web fundamental concept and tags
PPTX
Introduction to HTML5
PPTX
HTML Basics
PPTX
(Fast) Introduction to HTML & CSS
PPTX
HTML, CSS and Java Scripts Basics
PPTX
Introduction to html course digital markerters
PPT
html
PPTX
Chapter 2 - Introduction to HTML (Basic Structures and Syntax).pptx

More Related Content

PPTX
Introduction to HTML
PDF
Web development using html 5
PPT
Html introduction
KEY
Html intro
PPTX
Web Development Using CSS3
PDF
Web Development Using CSS3
DOC
Css introduction
PPTX
Web Page Designing Using HTML
Introduction to HTML
Web development using html 5
Html introduction
Html intro
Web Development Using CSS3
Web Development Using CSS3
Css introduction
Web Page Designing Using HTML

What's hot

PDF
Introduction to Html by Ankitkumar Singh
PDF
What is HTML - An Introduction to HTML (Hypertext Markup Language)
PPTX
PPTX
Html
PPTX
HTML Basics 1 workshop
PPTX
HTML, CSS, JavaScript for beginners
PDF
HTML Lecture Part 1 of 2
PDF
Intro to HTML and CSS basics
PPT
Lecture1and2
PPTX
Css module1
PPTX
PPTX
Html 5
PPTX
PPTX
Unit 1wt
PPTX
Web fundamental concept and tags
PPTX
Introduction to HTML5
PPTX
HTML Basics
PPTX
(Fast) Introduction to HTML & CSS
PPTX
HTML, CSS and Java Scripts Basics
PPTX
Introduction to html course digital markerters
Introduction to Html by Ankitkumar Singh
What is HTML - An Introduction to HTML (Hypertext Markup Language)
Html
HTML Basics 1 workshop
HTML, CSS, JavaScript for beginners
HTML Lecture Part 1 of 2
Intro to HTML and CSS basics
Lecture1and2
Css module1
Html 5
Unit 1wt
Web fundamental concept and tags
Introduction to HTML5
HTML Basics
(Fast) Introduction to HTML & CSS
HTML, CSS and Java Scripts Basics
Introduction to html course digital markerters

Similar to Java script and html new

PPT
html
PPTX
Chapter 2 - Introduction to HTML (Basic Structures and Syntax).pptx
PPTX
html.pptx
PPT
HTML & CSS.ppt
PPT
html and css- 23091 3154 458-5d4341a0.ppt
PPTX
Workshop 2 Slides.pptx
PPTX
PDF
Html & Html5 from scratch
DOCX
Lesson A.1 - Introduction to Web Development.docx
DOCX
Computer application html
PPTX
Basic Html Knowledge for students
PPTX
Lab1_HTML.pptx
PPSX
Html introduction
DOCX
Html.docx
PPTX
Html Workshop
PPTX
EBRE TABOR UNIVERSITY Gafat Institute of Technology Department of Information...
PPTX
Frontend Devlopment internship batch 2024-2.pptx
PPTX
Frontend Devlopment internship batch 2024.pptx
PDF
Html full
PPTX
FYBSC IT Web Programming Unit I HTML 5 & andcss
html
Chapter 2 - Introduction to HTML (Basic Structures and Syntax).pptx
html.pptx
HTML & CSS.ppt
html and css- 23091 3154 458-5d4341a0.ppt
Workshop 2 Slides.pptx
Html & Html5 from scratch
Lesson A.1 - Introduction to Web Development.docx
Computer application html
Basic Html Knowledge for students
Lab1_HTML.pptx
Html introduction
Html.docx
Html Workshop
EBRE TABOR UNIVERSITY Gafat Institute of Technology Department of Information...
Frontend Devlopment internship batch 2024-2.pptx
Frontend Devlopment internship batch 2024.pptx
Html full
FYBSC IT Web Programming Unit I HTML 5 & andcss

Recently uploaded

PPTX
How to use search_read method in Odoo 18
PDF
Projecte de la porta d'i5B: Els animals marins
PPTX
Basics in Phytochemistry, Extraction, Isolation methods, Characterisation etc.
PDF
DHA/HAAD/MOH/DOH OPTOMETRY MCQ PYQ. .pdf
PPTX
2025-2026 History in your Hands Class 4 December 2025 January 2026 .pptx
PPTX
PURPOSIVE SAMPLING IN EDUCATIONAL RESEARCH RACHITHRA RK.pptx
PPTX
Campfens "The Data Qualify Challenge: Publishers, institutions, and funders r...
PDF
M.Sc. Nonchordates Complete Syllabus PPT | All Important Topics Covered
PPTX
AI_in_Daily_Life_Presentation and more.pptx
PPTX
TAMIS & TEMS - HOW, WHY and THE STEPS IN PROCTOLOGY
PDF
Models of Teaching - TNTEU - B.Ed I Semester - Teaching and Learning - BD1TL ...
DOCX
Mobile applications Devlopment ReTest year 2025-2026
PDF
Analyzing the data of your initial survey
PDF
1ST APPLICATION FOR ANNULMENT (4)8787666.pdf
PDF
Digital Wellness in University Communities: Libraries as Guardians of Healthy...
PPTX
ATTENTION -PART 2.pptx Shilpa Hotakar for I semester BSc students
PPTX
Pain. definition, causes, factor influencing pain & pain assessment.pptx
PPTX
Pig- piggy bank in Big Data Analytics.ppt.pptx
PPTX
Unit I — Introduction to Anatomical Terms and Organization of the Human Body
PPTX
ICH Harmonization A Global Pathway to Unified Drug Regulation.pptx
How to use search_read method in Odoo 18
Projecte de la porta d'i5B: Els animals marins
Basics in Phytochemistry, Extraction, Isolation methods, Characterisation etc.
DHA/HAAD/MOH/DOH OPTOMETRY MCQ PYQ. .pdf
2025-2026 History in your Hands Class 4 December 2025 January 2026 .pptx
PURPOSIVE SAMPLING IN EDUCATIONAL RESEARCH RACHITHRA RK.pptx
Campfens "The Data Qualify Challenge: Publishers, institutions, and funders r...
M.Sc. Nonchordates Complete Syllabus PPT | All Important Topics Covered
AI_in_Daily_Life_Presentation and more.pptx
TAMIS & TEMS - HOW, WHY and THE STEPS IN PROCTOLOGY
Models of Teaching - TNTEU - B.Ed I Semester - Teaching and Learning - BD1TL ...
Mobile applications Devlopment ReTest year 2025-2026
Analyzing the data of your initial survey
1ST APPLICATION FOR ANNULMENT (4)8787666.pdf
Digital Wellness in University Communities: Libraries as Guardians of Healthy...
ATTENTION -PART 2.pptx Shilpa Hotakar for I semester BSc students
Pain. definition, causes, factor influencing pain & pain assessment.pptx
Pig- piggy bank in Big Data Analytics.ppt.pptx
Unit I — Introduction to Anatomical Terms and Organization of the Human Body
ICH Harmonization A Global Pathway to Unified Drug Regulation.pptx

Java script and html new

  • 1.
  • 2.
    HTML• HTML standsfor Hyper Text Markup Language• HTML describes the structure of a Web page• HTML consists of a series of elements• HTML elements tell the browser how to display the content• HTML elements are represented by tags• HTML tags label pieces of content such as "heading", "paragraph", "table", and soon• Browsers do not display the HTML tags, but use them to render the content ofthe page• What is Website, WebPage and Internet
  • 3.
    Use of html•First developed by Tim Berners-Lee in 1990, HTML is short forHyperText Markup Language. HTML is used to create electronicdocuments (called pages) that are displayed on the World Wide Web.Each page contains a series of connections to other pages calledhyperlinks.
  • 4.
    First HTML PAGE•<!DOCTYPE html><html><head><title>Page Title</title></head><body><h1>This is a Heading</h1><p>This is a paragraph.</p></body></html>
  • 5.
    HTML Document•The <!DOCTYPEhtml> declaration defines this document tobe HTML5•The <html> element is the root element of an HTML page•The <head> element contains meta information about thedocument•The <title> element specifies a title for the document•The <body> element contains the visible page content•The <h1> element defines a large heading•The <p> element defines a paragraph
  • 6.
    HTML TagsHTML TagsHTMLtags are element names surrounded by angle brackets:<tagname>content goes here...</tagname>•HTML tags normally come in pairs like <p> and </p>•The first tag in a pair is the start tag, the second tag is the end tag•The end tag is written like the start tag, but with a forward slash inserted before thetag name
  • 8.
    HTML HeadingsHTML headingsare defined with the <h1> to <h6> tags.<h1> defines the most important heading.<h6> defines the least important heading:Example<h1>This is heading 1</h1><h2>This is heading 2</h2><h3>This is heading 3</h3>
  • 9.
    HTML ParagraphsHTML paragraphsare defined with the <p> tag:Example<p>This is a paragraph.</p><p>This is another paragraph.</p>
  • 10.
    HTML LinksHTML linksare defined with the <a> tag:Example<a href="https://www.w3schools.com">This is a link</a>
  • 11.
    HTML ImagesHTML imagesare defined with the <img> tag.The source file (src), alternative text (alt), width, and heightare provided as attributes:Example<img src=“day01.jpg" alt="W3Schools.com" width="104" height="142">
  • 12.
  • 13.
    HTML Active ControlsHTMLButtonsHTML buttons are defined with the <button> tag:Example<button>Click me</button>
  • 14.
    HTML ListsHTML listsare defined with the <ul> (unordered/bullet list) or the <ol> (ordered/numberedlist) tag, followed by <li> tags (list items):Example<ul><li>Coffee</li><li>Tea</li><li>Milk</li></ul><ol><li>Coffee</li><li>Tea</li><li>Milk</li>
  • 15.
    Empty HTML ElementsHTMLelements with no content are called emptyelements.<br> is an empty element without a closing tag (the<br> tag defines a line break):Example<p>This is a <br> paragraph with a linebreak.</p>
  • 16.
    HTML Attributes• AllHTML elements can have attributes• Attributes provide additional information about an element• Attributes are always specified in the start tag• Attributes usually come in name/value pairs like: name="value“• <a href="https://www.w3schools.com">This is a link</a>• <img src="img_girl.jpg" width="500" height="600">• <p style="color:red">This is a paragraph.</p>• <p title="I'm a tooltip">This is a paragraph.</p>• <p title='John "ShotGun" Nelson'>
  • 17.
  • 18.
    The HTML StyleAttributeSetting the style of an HTML element, can be done with thestyle attribute.The HTML style attribute has the following syntax:<tagname style="property:value;">The property is a CSS property. The value is a CSS value.
  • 19.
    Background ColorThe CSSbackground-color property defines the background colorfor an HTML element.This example sets the background color for a page to powderblue:Example<body style="background-color:powderblue;"><h1>This is a heading</h1><p>This is a paragraph.</p></body>
  • 20.
    Text ColorThe CSScolor property defines the text color for an HTML element:Example<h1 style="color:blue;">This is a heading</h1><p style="color:red;">This is a paragraph.</p>
  • 21.
    Text SizeThe CSSfont-size property defines the text size for an HTMLelement:Example<h1 style="font-size:300%;">This is a heading</h1><p style="font-size:160%;">This is a paragraph.</p>
  • 22.
    Text AlignmentThe CSStext-align property defines the horizontal textalignment for an HTML element:Example<h1 style="text-align:center;">Centered Heading</h1><p style="text-align:center;">Centered paragraph.</p>
  • 23.
    In the previouschapter, you learned about the HTML style attribute.HTML also defines special elements for defining text with a special meaning.HTML uses elements like <b> and <i> for formatting output, like bold or italic text.Formatting elements were designed to display special types of text:•<b> - Bold text•<strong> - Important text•<i> - Italic text•<em> - Emphasized text•<mark> - Marked text•<small> - Small text•<del> - Deleted text•<ins> - Inserted text•<sub> - Subscript text•<sup> - Superscript text
  • 24.
    Quotes, Abbr andAddress• <p>Here is a quote from WWF's website:</p><blockquote cite="http://www.worldwildlife.org/who/index.html">For 50 years, WWF has been protecting the future of nature. The world's leading conservation organization, WWFworks in 100 countries and is supported by 1.2 million members in the United States and close to 5 million globally.</blockquote>• Abbreviation• <p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p>• Address• <address>Written by John Doe.<br>Visit us at:<br>Example.com<br>Box 564, Disneyland<br>USA</address>
  • 25.
  • 26.
  • 27.
    Background / ForegroundColor•Example•<h1 style="background-color:DodgerBlue;">HelloWorld</h1><p style="background-color:Tomato;">Lorem ipsum...</p>•Text Color• <h1 style="color:Tomato;">Hello World</h1><p style="color:DodgerBlue;">Lorem ipsum...</p><p style="color:MediumSeaGreen;">Ut wisi enim...</p>
  • 28.
    Border Color• Youcan set the color of borders:• Hello World• Hello World• Hello World• Example• <h1 style="border:2px solid Tomato;">Hello World</h1><h1 style="border:2px solid DodgerBlue;">Hello World</h1><h1 style="border:2px solid Violet;">Hello World</h1>
  • 33.
    HyperLinks• HTML linksare hyperlinks.• You can click on a link and jump to another document.• When you move the mouse over a link, the mouse arrow will turninto a little hand.• Note: A link does not have to be text. It can be an image or any otherHTML element.• <a href="url">link text</a>• <a href="html_images.asp">HTML Images</a>
  • 34.
  • 35.
    Styling HTML withCSSCSS stands for Cascading Style Sheets.CSS describes how HTML elements are to be displayed on screen,paper, or in other media.CSS saves a lot of work. It can control the layout of multiple webpages all at once.CSS can be added to HTML elements in 3 ways:•Inline - by using the style attribute in HTML elements•Internal - by using a <style> element in the <head> section•External - by using an external CSS file
  • 36.
    Inline CSSAn inlineCSS is used to apply a unique style to a single HTML element.An inline CSS uses the style attribute of an HTML element.This example sets the text color of the <h1> element to blue:Example<h1 style="color:blue;">This is a Blue Heading</h1>
  • 37.
    Internal CSSAn internalCSS is used to define a style for a single HTML page.An internal CSS is defined in the <head> section of an HTML page, within a <style> element:Example<!DOCTYPE html><html><head><style>body {background-color: powderblue;}h1 {color: blue;}p {color: red;}</style></head><body><h1>This is a heading</h1> <p>This is a paragraph.</p></body></html>
  • 38.
    External CSSAn externalstyle sheet is used to define the style for many HTML pages.With an external style sheet, you can change the look of an entire web site, bychanging one file!To use an external style sheet, add a link to it in the <head> section of the HTML page:<!DOCTYPE html><html><head><link rel="stylesheet" href="styles.css"></head><body><h1>This is a heading</h1><p>This is a paragraph.</p></body>
  • 39.
    StyleSheet Attributes•Use theHTML style attribute for inline styling•Use the HTML <style> element to define internal CSS•Use the HTML <link> element to refer to an external CSS file•Use the HTML <head> element to store <style> and <link> elements•Use the CSS color property for text colors•Use the CSS font-family property for text fonts•Use the CSS font-size property for text sizes•Use the CSS border property for borders•Use the CSS padding property for space inside the border•Use the CSS margin property for space outside the border
  • 40.
    • <style>a:link {color:green; background-color: transparent; text-decoration: none;}a:visited {color: pink; background-color: transparent; text-decoration: none;}a:hover {color: red; background-color: transparent; text-decoration: underline;}a:active {color: yellow;background-color: transparent;text-decoration: underline;}Style for Hyperlink
  • 41.
    HTML Links -The target AttributeThe target attribute specifies where to open the linked document.The target attribute can have one of the following values:•_blank - Opens the linked document in a new window or tab•_self - Opens the linked document in the same window/tab as itwas clicked (this is default)•_parent - Opens the linked document in the parent frame•_top - Opens the linked document in the full body of the window•framename - Opens the linked document in a named frame<a href="https://www.w3schools.com/" target="_blank">Visit W3Schools!</a>
  • 42.
  • 43.
    HTML Images• <!DOCTYPEhtml><html><head><style>img {width: 100%;}</style></head><body><img src="html5.gif" alt="HTML5 Icon" width="128" height="128"><img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;"></body></html>The width, height, and style attributes are valid in HTML.However, we suggest using the style attribute. It prevents styles sheets from changing the size of images:
  • 44.
    Image MapsThe <map>tag defines an image-map. An image-map is an image with clickable areas.In the image below, click on the computer, the phone, or the cup of coffee:<img src="workplace.jpg" alt="Workplace" usemap="#workmap"><map name="workmap"><area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm"><area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm"><area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm"></map>
  • 45.
  • 46.
    TableCompany Contact CountryAlfredsFutterkiste Maria Anders GermanyCentro comercial Moctezuma Francisco Chang MexicoErnst Handel Roland Mendel AustriaIsland Trading Helen Bennett UKLaughing Bacchus Winecellars Yoshi Tannamuri CanadaMagazzini Alimentari Riuniti Giovanni Rovelli Italy
  • 47.
    Example• <table style="width:100%"><tr><th>Firstname</th><th>Lastname</th><th>Age</th></tr><tr><td>Jill</td> <td>Smith</td> <td>50</td></tr><tr><td>Eve</td> <td>Jackson</td> <td>94</td></tr></table>
  • 48.
    HTML Table -Adding a BorderIf you do not specify a border for the table, it will be displayedwithout borders.A border is set using the CSS border property:Exampletable, th, td {border: 1px solid black;}table, th, td {border: 1px solid black;border-collapse: collapse;}
  • 49.
    HTML Table -Left-align HeadingsBy default, table headings are bold and centered.To left-align the table headings, use the CSS text-align propExampleth {text-align: left;}
  • 50.
    HTML Table -Cells that Span Many ColumnsTo make a cell span more than one column, use the colspan attribute:Example<table style="width:100%"><tr><th>Name</th><th colspan="2">Telephone</th></tr><tr><td>Bill Gates</td><td>55577854</td><td>55577855</td></tr></table>
  • 51.
    HTML Table -Cells that Span Many RowsTo make a cell span more than one row, use the rowspan attribute:Example<table style="width:100%"><tr><th>Name:</th><td>Bill Gates</td></tr><tr><th rowspan="2">Telephone:</th><td>55577854</td></tr><tr><td>55577855</td></tr></table>
  • 52.
    HTML Table -Adding a CaptionTo add a caption to a table, use the <caption> tag:Example<table style="width:100%"><caption>Monthly savings</caption><tr><th>Month</th> <th>Savings</th></tr><tr><td>January</td> <td>$100</td></tr><tr><td>February</td> <td>$50</td></tr>
  • 53.
    javaScript• Why StudyJavaScript?• JavaScript is one of the 3 languages all web developers must learn:• 1. HTML to define the content of web pages• 2. CSS to specify the layout of web pages• 3. JavaScript to program the behavior of web pages
  • 54.
    First JavaScript• <!DOCTYPEhtml>• <html>• <body>• <h2>JavaScript in Body</h2>• <p id="demo"></p>• <script>• document.getElementById("demo").innerHTML = "MyFirst JavaScript";• </script>• </body>
  • 55.
    JavaScript Function• <!DOCTYPEhtml><html><head><script>function myFunction() {document.getElementById("demo").innerHTML = "Paragraph changed.";}</script></head><body>• <h1>A Web Page</h1><p id="demo">A Paragraph</p><button type="button" onclick="myFunction()">Try it</button>• </body></html>
  • 56.
    JavaScript Can ChangeHTML ContentOne of many JavaScript HTML methods is getElementById().This example uses the method to "find" an HTML element (withid="demo") and changes the element content (innerHTML) to"Hello JavaScript":<!DOCTYPE html><html><body><h2>What Can JavaScript Do?</h2><p id="demo">JavaScript can change HTML content.</p><button type="button"onclick='document.getElementById("demo").innerHTML = "HelloJavaScript!"'>Click Me!</button></body></html>
  • 57.
    Light bulb• <!DOCTYPEhtml>• <html>• <body>• <h2>What Can JavaScript Do?</h2>• <p>JavaScript can change HTML attribute values.</p>• <p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>• <button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>• <img id="myImage" src="pic_bulboff.gif" style="width:100px">• <button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>• </body>• </html>
  • 58.
    Changing html cstyle•<!DOCTYPE html>• <html>• <body>• <h2>What Can JavaScript Do?</h2>• <p id="demo">JavaScript can change the style of an HTML element.</p>• <button type="button"onclick="document.getElementById('demo').style.fontSize='35px'">ClickMe!</button>• </body>• </html>
  • 59.
    Hiding html content•<!DOCTYPE html>• <html>• <body>• <h2>What Can JavaScript Do?</h2>• <p id="demo">JavaScript can hide HTML elements.</p>• <button type="button"onclick="document.getElementById('demo').style.display='none'">ClickMe!</button>• </body>• </html>
  • 60.
    External Call ofJavaScriptExternal scripts are practical when the same code is used in many different web pages.JavaScript files have the file extension .js.To use an external script, put the name of the script file in the src (source) attribute ofa <script> tag:Example<script src="myScript.js"></script>Try it Yourself »You can place an external script reference in <head> or <body> as you like.The script will behave as if it was located exactly where the <script> tag is located.External scripts cannot contain <script> tags.
  • 61.
    CODE• <!DOCTYPE html>•<html>• <body>• <h2>External JavaScript</h2>• <p id="demo">A Paragraph.</p>• <button type="button"onclick="myFunction()">Try it</button>• <p>(myFunction is stored in an external filecalled "myScript.js")</p>• <script src="Script1.js"></script>• </body>// JavaScript source codefunction myFunction() {document.getElementById("demo").innerHTML = "I am called from external file";}
  • 62.
    External JavaScript Advantages•Placing scripts in external files has some advantages:• It separates HTML and code• It makes HTML and JavaScript easier to read and maintain• Cached JavaScript files can speed up page loads• To add several script files to one page - use several script tags:
  • 63.
    JavaScript Display PossibilitiesJavaScriptcan "display" data in different ways:•Writing into an HTML element, using innerHTML.•Writing into the HTML output using document.write()•Writing into an alert box, using window.alert().•Writing into the browser console, using console.log(
  • 64.
    1. Using innerHTMLToaccess an HTML element, JavaScript can use the document.getElementById(id) method.The id attribute defines the HTML element. The innerHTML property defines the HTML content:Example<!DOCTYPE html><html><body><h1>My First Web Page</h1><p>My First Paragraph</p><p id="demo"></p><script>document.getElementById("demo").innerHTML = 5 + 6;</script></body></html>
  • 65.
    2. Document write•<!DOCTYPE html><html><body><h1>My First Web Page</h1><p>My first paragraph.</p><script>document.write(5 + 6);</script></body></html>
  • 66.
    3. window.alert()• <!DOCTYPEhtml><html><body><h1>My First Web Page</h1><p>My first paragraph.</p><script>window.alert(5 + 6);</script></body></html>
  • 67.
    Semicolons ;• Semicolonsseparate JavaScript statements.• Add a semicolon at the end of each executablestatement:• var a, b, c; // Declare 3 variablesa = 5; // Assign the value 5 to ab = 6; // Assign the value 6 to bc = a + b; // Assign the sum of a and b to c• When separated by semicolons, multiple statements onone line are allowed:• a = 5; b = 6; c = a + b;
  • 68.
    • <!DOCTYPE html>•<html>• <body>• <h2>JavaScript Statements</h2>• <p>Multiple statements on one line is allowed.</p>• <p id="demo1"></p>• <script>• var a, b, c;• a = 5; b = 6; c = a + b;• document.getElementById("demo1").innerHTML = c;• </script></body>• </html>
  • 69.
    Code blocks• <!DOCTYPEhtml>• <html>• <body>• <h2>JavaScript Statements</h2>• <p>JavaScript code blocks are written between { and }</p>• <button type="button" onclick="myFunction()">Click Me!</button>• <p id="demo1"></p> <p id="demo2"></p>• <script>• function myFunction() {• document.getElementById("demo1").innerHTML = "Hello COMSATS!";• document.getElementById("demo2").innerHTML = “How are all?";• }• </script></body>• </html>
  • 70.
    Keyword Descriptionbreak Terminatesa switch or a loopcontinue Jumps out of a loop and starts at the topdebugger Stops the execution of JavaScript, and calls (ifavailable) the debugging functiondo ... while Executes a block of statements, and repeats theblock, while a condition is truefor Marks a block of statements to be executed, aslong as a condition is truefunction Declares a functionif ... else Marks a block of statements to be executed,depending on a conditionreturn Exits a functionswitch Marks a block of statements to be executed,depending on different casestry ... catch Implements error handling to a block ofstatementsvar Declares a variable
  • 71.
    JS Strings• <html><body>• <h2>JavaScript Strings</h2>• <p>You can use quotes inside a string, as long as they don't match the quotessurrounding the string.</p>• <p id="demo"></p>• <script>• var answer1 = "It's alright";• var answer2 = "He is called 'Johnny'";• var answer3 = 'He is called "Johnny"';• document.getElementById("demo").innerHTML =• answer1 + "<br>" + answer2 + "<br>" + answer3;• document.getElementById("demo").innerHTML = "<br>" + "String length is " +answer3.length;• </script></body> </html>
  • 72.
    Special CharactersThe stringwill be chopped to "We are the so-called ".The solution to avoid this problem, is to use the backslash escape character.The backslash () escape character turns special characters into string characters:Code Result Description' ' Single quote" " Double quote Backslash<body><h2>JavaScript Strings</h2><p>The escape sequence " inserts a double quote in a string.</p><p id="demo"></p><script>var x = "We are the so-called "Vikings" from the north.";document.getElementById("demo").innerHTML = x;</script></body>
  • 73.
    Strings Can beObjectsNormally, JavaScript strings are primitive values, created from literals:var firstName = “xyz";But strings can also be defined as objects with the keyword new:var firstName = new String(“xyz");Examplevar x = “xyz";var y = new String(“xyz");// typeof x ??// typeof y ??
  • 74.
    String MethodsFinding aString in a StringThe indexOf() method returns the index of (the position of) the first occurrenceof a specified text in a string:Examplevar str = "Please locate where 'locate' occurs!";var pos = str.indexOf("locate");Searching for a String in a StringThe search() method searches a string for a specified value and returns the positionof the match:Examplevar str = "Please locate where 'locate' occurs!";var pos = str.search("locate");Extracting String PartsThere are 3 methods for extracting a part of a string:•slice(start, end)•substring(start, end)•substr(start, length)•Replace (“old text”,”new text”)
  • 75.
    String Methods• String.toUpperCase()and String.toLowerCase()• String.Concat() or use + Operator• String.trim()• String.charAt(SomeIndex)• String.charCodeAt(someindex) returns ASCII Code• String[index] or String[index] = ‘x’• Split ()• var txt = "a,b,c,d,e"; // Stringtxt.split(","); // Split on commastxt.split(" "); // Split on spacestxt.split("|");
  • 76.
    JS Arrays<!DOCTYPE html><html><body><h2>JavaScriptArrays</h2><p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p><p id="demo"></p><script>var cars = ["Saab", "Volvo", "BMW"];cars[0] = "Opel";document.getElementById("demo").innerHTML = cars;</script></body></html>
  • 77.
    Array Elements CanBe Objects• JavaScript variables can be objects. Arrays are specialkinds of objects.• Because of this, you can have variables of different typesin the same Array.• You can have objects in an Array. You can have functionsin an Array. You can have arrays in an Array:• myArray[0] = Date.now;myArray[1] = myFunction;myArray[2] = myCars;Array Properties and MethodsThe real strength of JavaScript arrays are thebuilt-in array properties and methods:Examplesvar x = cars.length; // The length propertyreturns the number of elementsvar y = cars.sort(); // The sort() methodsorts arrays
  • 78.
    Looping through Arrays•<body>• <h2>JavaScript Arrays</h2>• <p>The best way to loop through an array is using a standard for loop:</p>• <p id="demo"></p>• <script>• var fruits, text, fLen, i;• fruits = ["Banana", "Orange", "Apple", "Mango"];• fruits.push("Lemon"); fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits• fLen = fruits.length;• text = "<ul>";• for (i = 0; i < fLen; i++) {• text += "<li>" + fruits[i] + "</li>"; }• text += "</ul>";• document.getElementById("demo").innerHTML = text;• </script>• </body>
  • 79.
    Sorting Arrays• <body>•<h2>JavaScript Array Sort</h2>• <p>Click the buttons to sort the array alphabetically or numerically.</p>• <button onclick="myFunction1()">Sort Alphabetically</button>• <button onclick="myFunction2()">Sort Numerically</button>• <p id="demo"></p>• <script>• var points = [40, 100, 1, 5, 25, 10];• document.getElementById("demo").innerHTML = points;• function myFunction1() {• points.sort();• document.getElementById("demo").innerHTML = points; }• function myFunction2() {• points.sort(function (a, b) { return a - b });• document.getElementById("demo").innerHTML = points;• } </script> </body>
  • 80.
    JS DatesDate objectsare created with the new Date() constructor.There are 4 ways to create a new date object:new Date()new Date(year, month, day, hours, minutes, seconds, millnew Date(milliseconds)new Date(date string)
  • 81.
    Date methodsMethod DescriptiongetFullYear()Get the year as a four digit number (yyyy)getMonth() Get the month as a number (0-11)getDate() Get the day as a number (1-31)getHours() Get the hour (0-23)getMinutes() Get the minute (0-59)getSeconds() Get the second (0-59)getMilliseconds() Get the millisecond (0-999)getTime() Get the time (milliseconds since January 1,1970)getDay() Get the weekday as a number (0-6)Date.now() Get the time. ECMAScript 5.
  • 82.
    Date methods<!DOCTYPE html><html><body><h2>JavaScriptgetMonth()</h2><p>The getMonth() method returns the month as a number:</p><p>You can use an array to display the name of the month:</p><p id="demo"></p><script>var d = new Date();var months =["January","February","March","April","May","June","July","August","September","October","November","December"];document.getElementById("demo").innerHTML = months[d.getMonth()];</script></body></html>
  • 83.
    JavaScript Form Validation•HTML form validation can be done by JavaScript.• If a form field (fname) is empty, this function alerts a message, and returns false,to prevent the form from being submitted:• JavaScript Example• function validateForm() {var x = document.forms["myForm"]["fname"].value;if (x == "") {alert("Name must be filled out");return false;}}
  • 84.
    Number Validation• <script>•function myFunction() {• var x, text;• // Get the value of the input field with id="numb"• x = document.getElementById("numb").value;• // If x is Not a Number or less than one or greater than 10• if (isNaN(x) || x < 1 || x > 10) {• text = "Input not valid";• } else {• text = "Input OK";• } document.getElementById("demo").innerHTML = text;• }• </script>
  • 85.
    Constraint Validation HTMLInput AttributesAttribute Descriptiondisabled Specifies that the input element should be disabledmax Specifies the maximum value of an input elementmin Specifies the minimum value of an input elementpattern Specifies the value pattern of an input elementrequired Specifies that the input field requires an elementtype Specifies the type of an input element
  • 86.
    Constraint Validation DOM•If an input field contains invalid data, display a message:• The checkValidity() Method• <input id="id1" type="number" min="100" max="300" required><button onclick="myFunction()">OK</button><p id="demo"></p><script>function myFunction() {var inpObj = document.getElementById("id1");if (!inpObj.checkValidity()) {document.getElementById("demo").innerHTML = inpObj.validationMessage;}}</script>Property DescriptioncheckValidity() Returns true if an input element contains valid data.setCustomValidity() Sets the validationMessage property of an input element.
  • 87.
    JavaScript EventsThere area lot of different types of events that can occur, for example:• The user clicking the mouse over a certain element or hovering the cursor over acertain element.• The user pressing a key on the keyboard.• The user resizing or closing the browser window.• A web page finishing loading.• A form being submitted.• A video being played, or paused, or finishing play.• An error occurring.You can gather from this (and from glancing at the MDN Event reference) that thereare a lot of events that can be responded to.Each available event has an event handler, which is a block of code (usually a JavaScriptfunction that you as a programmer create) that will be run when the event fires.
  • 88.
    JavaScript HTML EventsEventDescriptiononchange An HTML element has been changedonclick The user clicks an HTML elementonmouseover The user moves the mouse over an HTMLelementonmouseout The user moves the mouse away from anHTML elementonkeydown The user pushes a keyboard keyonload The browser has finished loading the page
  • 89.
    What can JavaScriptDo?Event handlers can be used to handle, and verify, user input, user actions, and browser actions:• Things that should be done every time a page loads• Things that should be done when the page is closed• Action that should be performed when a user clicks a button• Content that should be verified when a user inputs data• And more ...Many different methods can be used to let JavaScript work with events:• HTML event attributes can execute JavaScript code directly• HTML event attributes can call JavaScript functions• You can assign your own event handler functions to HTML elements• You can prevent events from being sent or being handled• And more ...
  • 90.
    Button Event<html><head><title> JavaScriptButton Event Query Selector </title></head><body><button>Change color</button><script>const btn = document.querySelector('button');function random(number) { return Math.floor(Math.random() * (number+1)); }btn.onclick = function() {const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';document.body.style.backgroundColor = rndCol;}</script></body></html>
  • 91.
    Events in JavaScript•Node.js is a very popular JavaScript runtime that enables developers to useJavaScript to build network and server-side applications.• The Node.js event model relies on listeners to listen for events and emitters to emitevents periodically — it doesn't sound that different, but the code is quite different,making use of functions like on() to register an event listener, and once() to registeran event listener that unregisters after it has run once. The HTTP connect event docsprovide a good example of use.• As another example, you can also use JavaScript to build cross-browseradd-ons — browser functionality enhancements —• using a technology called WebExtensions. The event model is similar to the webevents model, but a bit different — event listeners properties are camel-cased (suchas onMessage rather than onmessage), and need to be combined with theaddListener function. See the runtime.onMessage page for an example.
  • 92.
    How to Programan Event in Jscriptconst btn = document.querySelector('button'); btn.onclick = function() { const rndCol = 'rgb(' + random(255) +',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; }1. Use OnClick PropertyThe onclick property is the event handler property being used in this situation. It is essentially a property like anyother available on the button (e.g. btn.textContent, or btn.style), but it is a special type — when you set it to be equalto some code, that code is run when the event fires on the button.const btn = document.querySelector('button'); function bgChange() { const rndCol = 'rgb(' +random(255) + ',' + random(255) + ',' + random(255) + ')';document.body.style.backgroundColor = rndCol; }btn.onclick = bgChange;2. Use Event Handler using Named Function
  • 93.
    Practice: Other EventHandlersmake a local copy of Button_Event_Query_Selector,and open it in your browser. Now try changing btn.onclick to the following different values in turn, andobserving the results in the example:•btn.onfocus and btn.onblur — The color changes when the button is focused and unfocused; try pressing tab to focuson the button and press tab again to focus away from the button. These are often used to display information abouthow to fill in form fields when they are focused, or display an error message if a form field has just been filled in withan incorrect value.•btn.ondblclick — The color changes only when the button is double-clicked.•window.onkeypress, window.onkeydown, window.onkeyup — The color changes when a key is pressed on the keyboard.The keypress event refers to a general press (button down and then up), while keydown and keyup refer to just the keydown and key up parts of the keystroke, respectively. Note that it doesn't work if you try to register this eventhandler on the button itself — we've had to register it on the window object, which represents the entire browserwindow.•btn.onmouseover and btn.onmouseout — The color changes when the mouse pointer is moved so it begins hovering overthe button, or when pointer stops hovering over the button and moves off of it, respectively.
  • 94.
    +Note: Some eventsare very general and available nearly anywhere (forexample an onclick handler can be registered on nearly any element),whereas some are more specific and only useful in certain situations(for example it makes sense to use onplay only on specific elements,such as <video>).<button onclick="alert('Hello, this is my old-fashioned event handler!');">Pressme</button>
  • 95.
    Inline Events<html><head><meta charset="utf-8"><title>Randomcolor example — event handler attribute</title><style>button {margin: 10px};</style></head><body><button onclick="bgChange()">Change color</button><script>function random(number) {return Math.floor(Math.random()*number);}function bgChange() {const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';document.body.style.backgroundColor = rndCol;}</script></body></html>
  • 96.
    Event Coding GuideYoucan find HTML attribute equivalents for many of the event handler properties;however, you shouldn't use these — they are considered bad practice. It mightseem easy to use an event handler attribute if you are just doing something reallyquick, but they very quickly become unmanageable and inefficient.For a start, it is not a good idea to mix up your HTML and your JavaScript, as itbecomes hard to parse — keeping your JavaScript all in one place is better; if it is ina separate file you can apply it to multiple HTML documents.One button is OK, but what if you had 100 buttons? You'd have to add 100attributes to the file; it would very quickly turn into a maintenance nightmare. WithJavaScript, you could easily add an event handler function to all the buttons on thepage no matter how many there were, using something like this
  • 97.
  • 100.
    The newest typeof event mechanism is defined in the Document Object Model (DOM) Level 2 EventsSpecification, which provides browsers with a new function — addEventListener(). This functions in a similarway to the event handler properties, but the syntax is obviously different.addEventListener() andremoveEventListener()const btn = document.querySelector('button');function bgChange() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) +')';document.body.style.backgroundColor = rndCol; }btn.addEventListener('click', bgChange);Add_Event_Lister_HTMLInside the addEventListener() function, we specify two parameters — the name of the event we want to register thishandler for, and the code that comprises the handler function we want to run in response to it. Note that it is perfectlyappropriate to put all the code inside the addEventListener()btn.removeEventListener('click', bgChange);
  • 101.
    EventListener Advantages• forlarger, more complex programs it can improve efficiency to clean upold unused event handlers.• this allows you to have the same button performing different actions indifferent circumstances — all you have to do is add or remove eventhandlers as appropriate.• Second, you can also register multiple handlers for the same listener. Thefollowing two handlers wouldn't both be applied:myElement.onclick = functionA;myElement.onclick = functionB;The second line overwrites the value of onclick set by the first line. This would work, however:myElement.addEventListener('click', functionA);myElement.addEventListener('click', functionB);using DOM Listeners both functions will work on click
  • 102.
    Event Objects• Sometimesinside an event handler function, you might see aparameter specified with a name such as event, evt, or simply e. This iscalled the event object, and it is automatically passed to event handlersto provide extra features and information. For example, let's rewriteour random color example again slightly:function bgChange(e) { const rndCol = 'rgb(' + random(255) + ',' + random(255) +',' + random(255) + ')';e.target.style.backgroundColor = rndCol; console.log(e); }btn.addEventListener('click', bgChange);an event object, e, in the function, and in the function setting a background color style on e.target — whichis the button itself. The target property of the event object is always a reference to the element that theevent has just occurred upon. So in this example, we are setting a random background color on the button,not the page. Example
  • 103.
  • 104.
    JavaScript Examples• JavaScriptPopoUP• JavaScript Matrix• JavaScript Form
  • 105.
    JavaScript vs React.JS•Web apps are becoming increasingly complex and dynamic. Inresponse, new tools and libraries like React have been created tospeed up the process.• But how is developing a web app with React different than developingan app with just plain JavaScript?
  • 106.
    JavaScript• To setsome boundaries, let’s first define what we mean by "plain"JavaScript (also called "vanilla" JavaScript).• React is a library that defines the way apps are written. It does this bysetting very clear rules about how data can flow through the app, andhow the UI will adapt as a result of that changing data. There areother libraries that set similar boundaries, such as Angular and Vue.• Plain JavaScript (that is, JavaScript written without libraries) on theother hand, doesn’t set any rules about how data can be defined, orhow the UI can be changed. That makes apps written without theselibraries more freeform and customizable. But going this route canalso lead to problems down the road
  • 107.
    The major differencesSincethere are so many ways to write vanilla JS, it can be difficult to pindown a list of differences that applies to 100% of apps. But here we’lldefine some key differences that apply to many plain JS apps that arewritten without a framework.• How the user interface is first created• How functionality is split up across the app• How data is stored on the browser• How the UI is updated
  • 108.
    In plain JS,the initial user interface is generally created in HTMLon the server. Meaning,HTML is dynamically created on the server, and might looksomething like this:<div><h1>Grocery List</h1><ul><li>Milk</li><li>Bread</li><li>Eggs</li></ul></div>That gets sent to the web browser and displayed—no JavaScript needed yet!In contrast, a React app will start with a fixed HTML file that looks like this:<div id=“root”></div>How the user interface is first created
  • 109.
    UI in REACTInsteadof defining the initial UI on the server, the UI gets defined on the browser. So the app starts with a blankcontainer (a div in this case), and then the UI gets loaded into that container.The UI is defined by a component that returns JSX. JSX looks like HTML, but is actually JavaScript - and might looklike this:function GroceryList(props) {return (<div><h1>Grocery List</h1><ul><li>Milk</li><li>Bread</li><li>Eggs</li></ul></div>)};
  • 110.
    • The UIis defined by a component that returns JSX. JSX looks like HTML, but isactually JavaScript - and might look like this:function GroceryList(props) {return (<div><h1>Grocery List</h1><ul><li>Milk</li><li>Bread</li><li>Eggs</li></ul></div>)};

[8]ページ先頭

©2009-2025 Movatter.jp