Record the knowledge points you have recently learned.
HTML DOM (Document Object Model)#
Overview: When a web page is loaded, the browser creates a Document Object Model (DOM) for the page.
Finding HTML Elements#
Usually, HTML elements can be manipulated using JavaScript.
To do this, you must first find the element. There are three methods to do this:
- Find HTML element by id: var x=document.getElementById("intro");
- Find HTML element by tag name: var y=document.getElementsByTagName("p");
- Find HTML element by class name: var x=document.getElementsByClassName("intro");
Changing HTML Content#
Use the innerHTML property.
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
Changing HTML Style#
Use style
<body>
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
document.getElementById("p2").style.fontFamily="Arial";
document.getElementById("p2").style.fontSize="larger";
</script>
</body>
Using Events#
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Button</button>
</body>
Defining Functions and Binding Events in JavaScript
var funcc = function () {
alert("hello world")
}
var aa = document.getElementById('vv')
aa.onclick = funcc
Using addEventListener
document.getElementById('vv').addEventListener('click',funcc);
document.getElementById('vv').addEventListener('click',function () {
alert('hahah')
})
onload and onunload Events#
- The onload and onunload events are triggered when the user enters or leaves the page.
- The onload event can be used to detect the visitor's browser type and browser version, and load the correct version of the web page based on this information.
- The onload and onunload events can be used to handle cookies.
<body onload="checkCookies()">
<script>
function checkCookies(){
if (navigator.cookieEnabled==true){
alert("Cookies are enabled")
}
else{
alert("Cookies are disabled")
}
}
</script>
</body>
onchange Event#
The onchange event is often used in combination with input field validation.
<!-- The function is called when the content of the input field changes and the focus is removed from the input field -->
<input type="text" id="fname" onchange="upperCase()">
onmouseover, onmouseout, onmousedown, onmouseup Events#
- onmouseover: Triggered when the mouse is moved over an HTML element.
- onmouseout: Triggered when the mouse is moved away from an HTML element.
- onmousedown: Triggered when the mouse button is pressed down on an element.
- onmouseup: Triggered when the mouse button is released.
HTMLCollection Object#
Overview: The getElementsByTagName() method returns an HTMLCollection object. The HTMLCollection object is similar to an array that contains HTML elements. Elements in the collection can be accessed using an index (starting at 0).
var x = document.getElementsByTagName("p");
y = x[1]; // Access the second p element
NodeList Object#
Overview: The NodeList object is a collection of nodes (elements) obtained from the document.
Use the querySelectorAll property to obtain the object.
var myNodeList = document.querySelectorAll("p");
Elements can also be accessed using an index.
Difference Between NodeList and HTMLCollection#
- HTMLCollection elements can be accessed by name, id, or index.
- NodeList can only be accessed by index.
- Only the NodeList object contains attribute nodes and text nodes.
Browser Object Model (BOM)#
This object represents the browser window, and global variables are properties of the window object. Global functions are methods of the window object (including document).
Window Size#
- window.innerHeight - the inner height of the browser window (including scrollbars)
- window.innerWidth - the inner width of the browser window (including scrollbars)
Window Screen#
- screen.availWidth - the available width of the screen
- screen.availHeight - the available height of the screen
Window Location#
- location.hostname returns the domain name of the web host
- location.pathname returns the path and filename of the current page
- location.port returns the port of the web host (80 or 443)
- location.protocol returns the web protocol being used (http: or https:)
- location.href returns the URL of the current page
- location.assign(url) loads a new HTML document specified by the URL. It is similar to a link, redirecting to the specified URL and replacing the current page content. You can click the back button to return to the previous page.
- location.replace(url) replaces the current document with a new document specified by the URL. This method replaces the current window page, so there is no back button to return to the previous page.
Window History#
- history.back() - same as clicking the back button in the browser
- history.forward() - same as clicking the forward button in the browser
The history.go() method can also be used to implement forward and backward functionality
history.go(1); // go() with a parameter of 1 means go forward one page
history.go(-1); // go() with a parameter of -1 means go back one page
history.go(0); // go() with a parameter of 0 means refresh the page
Pop-up Windows#
Alert Box
alert()
alert("Alert box!");
Confirm Box
confirm()
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
Prompt Box
prompt() - When the prompt box appears, the user needs to input a value and click OK or Cancel to continue.
var person=prompt("Please enter your name");
if (person!=null && person!=""){
document.getElementById("demo").innerHTML=person;
}
JavaScript Timing Events#
- setInterval() - repeatedly executes a specified code snippet at a specified interval in milliseconds. It takes two parameters: the function and the interval in milliseconds.
- setTimeout() - executes a specified code snippet after a specified delay in milliseconds. It takes two parameters: the function and the delay in milliseconds.
To stop the timing events: clearInterval() and clearTimeout()
var myVar=setInterval(function(){myTimer()},1000);
function myTimer(){
alert("Hello");
}
function myStopFunction(){
clearInterval(myVar);
}
var myVar;
function myFunction()
{
myVar=setTimeout(function(){alert("Hello")},3000);
}
function myStopFunction()
{
clearTimeout(myVar);
}
Cookies#
Overview: Cookies are data stored in a text file on your computer. They are stored as key-value pairs.
Creating Cookies
document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT"; // The expires parameter is the expiration time of the cookie. By default, the cookie is deleted when the browser is closed.
document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/"; // The path parameter tells the browser the path of the cookie. By default, the cookie belongs to the current page.
Reading Cookies
var x = document.cookie;
Modifying Cookies
document.cookie="username=John Smith; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/"; // Similar to creating cookies, it overwrites the existing cookie.
Retrieving Cookies
If a new cookie is set, the old cookie will not be overwritten. The new cookie will be added to document.cookie. So, if you read document.cookie again, you will get the following data:
cookie1=value; cookie2=value;
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}