2024年12月26日 星期四

Javascript如何設定和取得Cookie?

在 JavaScript 中,可以使用 document.cookie 來設定和取得 Cookie。以下是設定和取得 Cookie 的方法:


1. 設定 Cookie

基本語法

javascript

document.cookie = "key=value; expires=date; path=path; domain=domain; secure; samesite=strict";

範例

javascript

// 設定一個簡單的 Cookie document.cookie = "username=Alice"; // 設定一個有過期時間的 Cookie document.cookie = "sessionToken=abc123; expires=Fri, 31 Dec 2024 23:59:59 GMT"; // 設定一個有效路徑的 Cookie document.cookie = "theme=dark; path=/"; // 設定跨域 Cookie (需伺服器支持) document.cookie = "authToken=xyz456; domain=example.com"; // 設定安全和 SameSite 屬性 document.cookie = "secureData=true; secure; samesite=strict";

2. 取得 Cookie

基本語法

javascript

const allCookies = document.cookie;

document.cookie 返回的是一個由分號分隔的字符串,其中包含所有可訪問的 Cookie。

範例

javascript

// 獲取所有 Cookie console.log(document.cookie); // 輸出: "username=Alice; theme=dark; sessionToken=abc123" // 解析特定 Cookie function getCookie(name) { const cookies = document.cookie.split("; "); for (let cookie of cookies) { const [key, value] = cookie.split("="); if (key === name) { return decodeURIComponent(value); // 解碼值 } } return null; // 找不到返回 null } // 使用範例 const username = getCookie("username"); console.log(username); // Alice

3. 刪除 Cookie

刪除 Cookie 的方式是設定相同名稱的 Cookie,但將其 expires 屬性設為過去的日期。

範例

javascript

// 刪除一個 Cookie document.cookie = "username=Alice; expires=Thu, 01 Jan 1970 00:00:00 GMT"; // 通用刪除函數 function deleteCookie(name, path = "/") { document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${path}`; } // 使用範例 deleteCookie("username");

4. 使用封裝函數處理 Cookie

為了方便操作 Cookie,可以封裝一組函數來處理。

javascript

// 設定 Cookie function setCookie(name, value, days = 7, path = "/") { const date = new Date(); date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); const expires = `expires=${date.toUTCString()}`; document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}; path=${path}`; } // 取得 Cookie function getCookie(name) { const cookies = document.cookie.split("; "); for (let cookie of cookies) { const [key, value] = cookie.split("="); if (key === name) { return decodeURIComponent(value); } } return null; } // 刪除 Cookie function deleteCookie(name, path = "/") { document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${path}`; } // 使用範例 setCookie("user", "Alice", 5); // 設定 Cookie,保存 5 天 console.log(getCookie("user")); // 獲取 Cookie 值 deleteCookie("user"); // 刪除 Cookie console.log(getCookie("user")); // null

注意事項

  1. Cookie 的大小限制

    • 每個 Cookie 的大小通常限制為 4KB。
    • 每個域名最多可以存儲約 20 個 Cookie。
  2. 安全性

    • 使用 secure 屬性可確保 Cookie 只能通過 HTTPS 傳輸。
    • 使用 samesite=strict 可防範跨站請求偽造(CSRF)。
  3. 跨域限制

    • Cookie 默認只適用於設置它的域名和路徑。
  4. 敏感數據

    • 不要在 Cookie 中存儲敏感數據,建議加密後再存。

這樣,你就可以方便地操作 Cookie 來儲存和管理用戶的數據。

Javascript FormData() 如何使用 ?

 FormData 是 JavaScript 中的內建對象,用於構建用戶提交的表單數據,並將其以鍵值對的形式傳遞到伺服器。它特別適合處理文件上傳和支持多部分表單數據的請求。


1. 基本用法

創建 FormData 對象

可以從現有的 <form> 元素中初始化,也可以手動構建。

javascript

// 從現有表單創建 FormData const formElement = document.querySelector("form"); const formData = new FormData(formElement); // 手動創建 FormData const manualFormData = new FormData(); manualFormData.append("username", "Alice"); manualFormData.append("age", "25");

2. FormData 方法

  • append(name, value, fileName):添加一個鍵值對到 FormData 對象中。
  • delete(name):刪除指定鍵名的數據。
  • get(name):獲取指定鍵名的第一個值。
  • getAll(name):獲取指定鍵名的所有值(返回數組)。
  • has(name):檢查是否包含指定鍵名。
  • set(name, value, fileName):設置指定鍵名的值(如果已存在則覆蓋)。

範例

javascript

const formData = new FormData(); // 添加數據 formData.append("username", "Alice"); formData.append("age", "25"); formData.append("hobbies", "reading"); formData.append("hobbies", "traveling"); // 可以添加多個值 // 獲取數據 console.log(formData.get("username")); // Alice console.log(formData.getAll("hobbies")); // ["reading", "traveling"] // 更新數據 formData.set("username", "Bob"); console.log(formData.get("username")); // Bob // 刪除數據 formData.delete("age"); console.log(formData.has("age")); // false

3. 文件上傳

FormData 非常適合處理文件上傳,尤其是與 <input type="file"> 配合使用。

範例

HTML:

html

<form id="uploadForm"> <input type="text" name="username" value="Alice" /> <input type="file" name="file" /> <button type="button" onclick="upload()">Upload</button> </form>

JavaScript:

javascript

function upload() { const form = document.getElementById("uploadForm"); const formData = new FormData(form); fetch("https://example.com/upload", { method: "POST", body: formData }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error:", error)); }

4. 遍歷 FormData

可以使用 for...of 迴圈來遍歷 FormData 對象中的鍵值對。

範例

javascript

const formData = new FormData(); formData.append("username", "Alice"); formData.append("age", "25"); for (const [key, value] of formData.entries()) { console.log(`${key}: ${value}`); } // 輸出: // username: Alice // age: 25

5. 與 Content-Type 頭的關係

  • 使用 FormData 時,不需要手動設置 Content-Typemultipart/form-data
  • 瀏覽器會自動為請求添加正確的 Content-Type 和邊界值。

錯誤示範

javascript

fetch("https://example.com/upload", { method: "POST", body: formData, headers: { "Content-Type": "multipart/form-data" } // 不要這樣做 });

正確用法

javascript

fetch("https://example.com/upload", { method: "POST", body: formData });

6. 使用場景

  1. 處理表單數據提交

    • 直接將表單的數據傳遞到伺服器。
  2. 文件上傳

    • 支持多文件和單文件上傳。
  3. 動態構建數據

    • 手動添加或修改需要發送的數據。

7. 注意事項

  1. 跨域請求

    • 確保伺服器設置了正確的 CORS 頭。
  2. 不支持 JSON 格式

    • 如果伺服器需要 JSON 格式數據,需要手動轉換:
      javascript

      const data = { username: "Alice", age: 25 }; fetch("https://example.com/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
  3. 文件限制

    • 瀏覽器可能對文件大小和數量有一定限制,需要檢查用戶選擇的文件是否符合條件。

總結

FormData 是處理表單和文件上傳的強大工具,通過簡單的 API 實現動態數據構建和提交。無需額外的序列化操作,非常適合應用於現代 Web 開發中需要和伺服器交互的場景。

Javascript 中如何用 JSON 序列化及反序列化

在 JavaScript 中,JSON 序列化和反序列化分別是指將 JavaScript 對象轉換為 JSON 字符串(序列化),以及將 JSON 字符串解析為 JavaScript 對象(反序列化)。這可以使用內建的 JSON 對象輕鬆完成。


1. JSON 序列化:JSON.stringify()

語法

javascript

JSON.stringify(value, replacer, space)
  • value:要序列化的 JavaScript 對象。
  • replacer(可選):一個函數或數組,用於過濾對象屬性。
  • space(可選):指定縮進的空格數量,用於格式化輸出的 JSON 字符串。

範例

javascript

const obj = { name: "Alice", age: 25, hobbies: ["reading", "traveling"], isStudent: false }; // 基本序列化 const jsonString = JSON.stringify(obj); console.log(jsonString); // 輸出: {"name":"Alice","age":25,"hobbies":["reading","traveling"],"isStudent":false} // 帶縮進的序列化(格式化) const formattedJsonString = JSON.stringify(obj, null, 2); console.log(formattedJsonString); /* 輸出: { "name": "Alice", "age": 25, "hobbies": [ "reading", "traveling" ], "isStudent": false } */

使用 replacer 過濾屬性

javascript

// 過濾某些屬性 const jsonStringWithFilter = JSON.stringify(obj, ["name", "age"]); console.log(jsonStringWithFilter); // 輸出: {"name":"Alice","age":25} // 使用函數自定義過濾 const jsonStringWithFunction = JSON.stringify(obj, (key, value) => { if (key === "age") return undefined; // 過濾掉 age return value; }); console.log(jsonStringWithFunction); // 輸出: {"name":"Alice","hobbies":["reading","traveling"],"isStudent":false}

2. JSON 反序列化:JSON.parse()

語法

javascript

JSON.parse(text, reviver)
  • text:要解析的 JSON 字符串。
  • reviver(可選):一個函數,用於轉換解析的結果。

範例

javascript

const jsonString = '{"name":"Alice","age":25,"hobbies":["reading","traveling"],"isStudent":false}'; // 基本反序列化 const obj = JSON.parse(jsonString); console.log(obj); // 輸出: { name: 'Alice', age: 25, hobbies: [ 'reading', 'traveling' ], isStudent: false }

使用 reviver 修改解析的值

reviver 函數接收兩個參數:keyvalue,可以用來轉換結果。

javascript

const objWithReviver = JSON.parse(jsonString, (key, value) => { if (key === "age") { return value + 1; // 年齡加 1 } return value; }); console.log(objWithReviver); // 輸出: { name: 'Alice', age: 26, hobbies: [ 'reading', 'traveling' ], isStudent: false }

3. JSON 序列化與反序列化的實用範例

儲存和讀取數據

javascript

// 模擬數據儲存到 localStorage const user = { id: 1, username: "Bob" }; localStorage.setItem("user", JSON.stringify(user)); // 從 localStorage 讀取數據 const savedUser = JSON.parse(localStorage.getItem("user")); console.log(savedUser); // 輸出: { id: 1, username: 'Bob' }

數據傳輸

序列化和反序列化經常用於網絡請求中:

  • 序列化:將 JavaScript 對象轉換為 JSON 字符串,發送到伺服器。
  • 反序列化:將伺服器返回的 JSON 字符串轉換為 JavaScript 對象。
javascript

// 模擬發送數據 const requestData = { message: "Hello" }; fetch("https://example.com/api", { method: "POST", body: JSON.stringify(requestData), headers: { "Content-Type": "application/json" } }); // 模擬接收數據 fetch("https://example.com/api") .then(response => response.json()) // 自動進行反序列化 .then(data => console.log(data));

注意事項

  1. JSON 格式要求

    • JSON 的鍵名必須是雙引號包裹的字符串。
    • 僅支持基本類型:字符串、數字、布爾值、null、數組和對象。
    • 不支持函數、undefined、Symbol 等。
  2. 循環引用問題

    • 如果對象中存在循環引用,JSON.stringify() 會拋出錯誤:
      javascript

      const obj = {}; obj.self = obj; JSON.stringify(obj); // Uncaught TypeError: Converting circular structure to JSON
  3. 安全性

    • 在解析不受信任的 JSON 字符串時,要防範惡意輸入。

總結

  • 序列化JSON.stringify() 將 JavaScript 對象轉換為 JSON 字符串。
  • 反序列化JSON.parse() 將 JSON 字符串轉換為 JavaScript 對象。

這些方法非常適合用於本地存儲、數據傳輸和動態處理數據。

2022年1月7日 星期五

[Javascript]在javascript端防範XSS攻擊

 在任何被掃瞄出來有XSS風險的物件,代入類似下列語法,把惡意的字串去除掉:

這邊的情況是a.text會接收到網頁上來自使用者的輸入的任何文字,怕a.text裡面會有惡意的javascript

a.text = a.text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/\'/g, '&#39;').replace(/\//g, '&#x2F;');






From: https://dotblogs.com.tw/kevinya/2018/12/19/103831

[javascript]檔案上傳以及圖片縮圖成指定的解析度範例

檔案上傳的時候,大多還要縮圖,以下是簡易範例:

Html:使用input type=file的fileupload1元件來做上傳,用隱藏欄位AdImage來做調整解析度的圖片的暫存區,用隱藏欄位AdName來當成新上傳檔案的檔案名稱,用div+img來顯示新上傳的圖片或是顯示從db讀出來的圖片(base64字串的圖片)

<div class="row">
	@using (Html.BeginForm("Edit", "AdUpdate", FormMethod.Post, new { @class = "form-horizontal", role = "form", id = "PostForm" }))
	{
		@Html.AntiForgeryToken()
		<input type="hidden" id="AdNum" name="AdNum" value="@ViewBag.AdNum">
		<input type="hidden" id="AdImage" name="AdImage">
		<input type="hidden" id="AdName" name="AdName">
		<div class="col-md-12">
			<div class="card" style="width:940px;">
				<div class="card-body">
					<h4>上方廣告圖片:<span id="fileName">@ViewBag.AdName</span></h4>
					<div class="row mt-4 mb-3">
						<div class="col-md-12">
							<div id="photo" class="align-left" style="width:905px;height:160px; background:#ccc;">
								<img src="@ViewBag.AdImage" />
							</div>
						</div>
					</div>
					<div class="row mt-4 mb-3" id="myTabContent">
						<div class="col-md-6">
							<div class="alert alert-danger alert-dismissable">
								<span style="color: #880000">圖片檔,寬限為905px,高限為160px。</span>
							</div>
						</div>
					</div>

					<div class="row mt-4 mb-3">
						<div class="col-md-2 col-md-offset-4">
							<label class="btn btn-success btn-file">
								<i class="fa fa-lg fa-folder-open"></i>&nbsp;<span>選擇檔案</span>
								<input type="file" id="fileUpload1" name="fileUpload1" style="display: none;">
							</label>
						</div>
						<div class="col-md-2" id="updateBtn">
							<label class="btn btn-warning" onclick="doUpdate('AdImage', 'AdName', 'fileName','PostForm')">
								<i class="fa fa-lg fa-upload"></i>&nbsp;<span>上傳</span>
							</label>
						</div>
						<div class="col-md-2">
							<label class="btn btn-block" onclick="location.reload()">
								<i class="fa fa-lg fa-close"></i>&nbsp;<span>取消</span>
							</label>
						</div>
					</div>
				</div>
			</div>
		</div>
	}
</div>


javascript端於document.ready先幫file upload元件加入onchange事件:SetFileUploadOnChangeEvent()

$(document).ready(function () {
	//設定file upload的 onchange event
	//addEventListener一定要搭配document.getElementById抓物件,用jquery $("#id")的方式抓物件不行
	document.getElementById("fileUpload1").addEventListener("change", function () {
		SetFileUploadOnChangeEvent(this.id, 'photo', 'AdImage', 'fileName', 905, 160);
	}, false);
});


以下是fileupload元件的change事件的function細節:SetFileUploadOnChangeEvent()
會先用imgCheck()檢查使用者上傳的圖片是否為jpg, png, ....
接著會用imgReSize()調整解析度
最後會將縮圖之後的圖片顯示在div+img

//****設定file upload的 onchange event****
//fileUploadId:上傳檔案的元件的id, imageHolderId:載入圖片的div,
//adImageId: base64字串的圖片, labelfileNameId: 顯示圖檔名稱的label的id
//labelfileNameId: 顯示檔案名稱的label的id
//Max_Width: 圖片的寬度, Max_Height:圖片的高度
function SetFileUploadOnChangeEvent(fileUploadId, imageHolderId, adImageId, labelfileNameId,
	Max_Width, Max_Height) {

	//檢查圖片格式
	//alert(fileUploadId);
	var errorMsg = imgCheck(fileUploadId);
	if (errorMsg.length > 0) {
		swal(errorMsg, "", "error");
		return;
	}
	//alert(typeof (FileReader));
	//確認有上傳檔案
	if (document.getElementById(fileUploadId).files.length != 0) {
		var image_holder = $("#" + imageHolderId);
		var AdImage = $("#" + adImageId);

		var reader = new FileReader();

		reader.onload = function (e) {
			imgReSize(e.target.result, imageHolderId, AdImage, fileUploadId,
				Max_Width, Max_Height, labelfileNameId);
		}
		image_holder.show();
		//alert('image_holder.show()');
		var fName = $("#" + fileUploadId)[0].files[0].name;
		//alert(fName);
		//var fSize = $(this)[0].files[0].size;
		$("#" + labelfileNameId).text(fName);

		// $("#fileSize").text(Math.round(fSize / 1024));
		reader.readAsDataURL($("#" + fileUploadId)[0].files[0]);

	} else {
		//alert(1000);
		alert("This browser does not support FileReader.");
	}
	//alert(2000);
	//});
}
//檢查上傳格式必須為png, jpg, jpeg
function imgCheck(fileUploadId) {
	var errMsg = '';
	//var ext = $("#fileUpload1").val().split('.').pop().toLowerCase();
	var ext = $("#" + fileUploadId).val().split('.').pop().toLowerCase();
	if ($.inArray(ext, ['png', 'jpg', 'jpeg']) == -1) {
		errMsg = '請上傳正確的圖片格式';
		$("#" + fileUploadId).val('');
	}
	return errMsg;
}
function imgReSize(source, imageHolderId, B64, fileUploadId, Max_Width, Max_Height, labelfileNameId) {
	var img = document.createElement("img");
	//alert('start resize');
	img.src = source;
	//影像RESIZE
	img.addEventListener('load', function () {
		var canvas = document.createElement("canvas");
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0);

		var MAX_WIDTH = Max_Width;
		var MAX_HEIGHT = Max_Height;
		var width = img.width;
		var height = img.height;

		//檢查圖片大小
		if (width != MAX_WIDTH || height != MAX_HEIGHT) {
			
			swal({
				title: "圖片不符合格式:" + MAX_WIDTH + " * " + MAX_HEIGHT + " px,確認繼續上傳?",
				type: "warning",
				showConfirmButton: true,
				showCancelButton: true,
				confirmButtonText: "Yes",
				cancelButtonText: "No",
				closeOnConfirm: true,
				closeOnCancel: true
			}, function (isConfirm) {
				if (isConfirm) {
					//確定繼續上傳
				}
				else {
					//中止上傳
					$("#" + fileUploadId + "").val('');
					var image_holder = $("#" + imageHolderId);
					image_holder.empty();
					$("#" + labelfileNameId).text('');
					return;
				}
			});
			
		}
		
		if (width > height) {
			if (width > MAX_WIDTH) {
				height *= MAX_WIDTH / width;
				width = MAX_WIDTH;
			}
		} else {
			if (height > MAX_HEIGHT) {
				width *= MAX_HEIGHT / height;
				height = MAX_HEIGHT;
			}
		}
		
		var ctx = canvas.getContext("2d");
		var Width = Max_Width;//預設網頁顯示圖片寬度
		var exifOrientation = '';
		// Check orientation in EXIF metadatas
		EXIF.getData(img, function () {
			var allMetaData = EXIF.getAllTags(this);
			exifOrientation = allMetaData.Orientation;
			//val orientation = ExifInterface(file.absolutePath).getAttribute(ExifInterface.TAG_ORIENTATION)
			console.log('Exif orientation: ' + exifOrientation);
		});
		//alert(333);
		// set proper canvas dimensions before transform & export
		if (jQuery.inArray(exifOrientation, [5, 6, 7, 8]) > -1) {
			canvas.width = height;
			canvas.height = width;
			//動態修改預設網頁顯示圖片寬度,讓高度在框內
			Width = Max_Height * (height / width);
		} else {
			canvas.width = width;
			canvas.height = height;
		}

		// transform context before drawing image
		switch (exifOrientation) {
			case 2:
				ctx.transform(-1, 0, 0, 1, width, 0);
				break;
			case 3:
				ctx.transform(-1, 0, 0, -1, width, height);
				break;
			case 4:
				ctx.transform(1, 0, 0, -1, 0, height);
				break;
			case 5:
				ctx.transform(0, 1, 1, 0, 0, 0);
				break;
			case 6:
				ctx.transform(0, 1, -1, 0, height, 0);
				break;
			case 7:
				ctx.transform(0, -1, -1, 0, height, width);
				break;
			case 8:
				ctx.transform(0, -1, 1, 0, 0, width);
				break;
			default:
				ctx.transform(1, 0, 0, 1, 0, 0);
		}
		ctx.drawImage(img, 0, 0, width, height);

		var dataurl = canvas.toDataURL("image/jpeg", 1);
		/*
		canvas.toBlob(function (blob) {
			$('#reFileSize').text(Math.round(blob.size / 1024));
		}, 'image/jpeg', 1);
		*/
		B64.val(dataurl);
		$("#" + imageHolderId).empty();

		$("<img />", {
			"width": Width,
			"src": dataurl
		}).appendTo($("#" + imageHolderId));
		//alert('fin')
	});
}


補充一下如何送出submit然後上傳縮圖之後的照片到db:
利用ajax將base64字串格式的圖片上傳到Db

//更新圖檔
//imgId:base64圖片字串物件的id, hidAdNameId: 檔案名稱隱藏欄位的id, labelfileNameId:檔案名稱的label的id
function doUpdate(imgId, hidAdNameId, labelfileNameId, formId) {
	//alert(111);
	$("#" + imgId).val($("#" + imgId).val().split(",")[1]);
	//alert($("#" + labelfileNameId).text());
	//alert(222);
	$("#" + hidAdNameId).val($("#" + labelfileNameId).text());

	if ($("#" + imgId).val() == '' || $("#" + hidAdNameId).val() == '') {
		swal("請上傳圖片!", "", "error");
	}
	var postUrl = '';
	postUrl = "/AdUpdate/Edit";
	$.ajax({
		type: 'Post',
		url: postUrl,
		data: $("#" + formId).serialize(),
		success: function (data) {
			if (data.success) {
				swal({
					title: '更新成功!',
					text: '',
					type: 'success'
				}, function () {
					location.reload();
				});
			} else {
				$(".validation-summary-valid ul").empty();
				for (var i = 0; i < data.errors.length; i++) {
					var error = data.errors[i];
					$(".validation-summary-valid ul").append($("<li>").text(error));
				}
			}
		}
	});
}





From: https://dotblogs.com.tw/kevinya/2019/02/19/103131

2019年10月15日 星期二

JavaScript HTML DOM Events

Reacting to Events

< !DOCTYPE html>
< html>
< body>

< h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!< /h1>

< /body>
< /html>



HTML Event Attributes

< !DOCTYPE html>
< html>
< body>

< button onclick="displayDate()">Try it< /button>

< /body>
< /html>



Assign Events Using the HTML DOM

< script>
document.getElementById("myBtn").onclick = displayDate;
< /script>



The onload and onunload Events

< body onload="checkCookies()">



The onchange Event

< input type="text" id="fname" onchange="upperCase()">




The onmouseover and onmouseout Events

< !DOCTYPE html>
< html>
< body>

< div onmouseover="mOver(this)" onmouseout="mOut(this)" 
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me< /div>

< script>
function mOver(obj) {
  obj.innerHTML = "Thank You"
}

function mOut(obj) {
  obj.innerHTML = "Mouse Over Me"
}
< /script>

< /body>
< /html> 




The click Events

< !DOCTYPE html>
< html>
< body>

< div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me< /div>

< script>
function mDown(obj) {
  obj.style.backgroundColor = "#1ec5e5";
  obj.innerHTML = "Release Me";
}

function mUp(obj) {
  obj.style.backgroundColor="#D94A38";
  obj.innerHTML="Thank You";
}
< /script>

< /body>
< /html> 



onfocus

< !DOCTYPE html>
< html>
< head>
< script>
function myFunction(x) {
  x.style.background = "yellow";
}
< /script>
< /head>
< body>

Enter your name: < input onfocus="myFunction(this)" type="text" />

< p>When the input field gets focus, a function is triggered which 
changes the background-color.< /p>

< /body>
< /html>



HTML DOM Events


Event Description Belongs To
abort The event occurs when the loading of a media is aborted UiEventEvent
afterprint The event occurs when a page has started printing, or if the print dialogue box has been closed Event
animationend The event occurs when a CSS animation has completed AnimationEvent
animationiteration The event occurs when a CSS animation is repeated AnimationEvent
animationstart The event occurs when a CSS animation has started AnimationEvent
beforeprint The event occurs when a page is about to be printed Event
beforeunload The event occurs before the document is about to be unloaded UiEventEvent
blur The event occurs when an element loses focus FocusEvent
canplay The event occurs when the browser can start playing the media (when it has buffered enough to begin) Event
canplaythrough The event occurs when the browser can play through the media without stopping for buffering Event
change The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <select>, and <textarea>) Event
click The event occurs when the user clicks on an element MouseEvent
contextmenu The event occurs when the user right-clicks on an element to open a context menu MouseEvent
copy The event occurs when the user copies the content of an element ClipboardEvent
cut The event occurs when the user cuts the content of an element ClipboardEvent
dblclick The event occurs when the user double-clicks on an element MouseEvent
drag The event occurs when an element is being dragged DragEvent
dragend The event occurs when the user has finished dragging an element DragEvent
dragenter The event occurs when the dragged element enters the drop target DragEvent
dragleave The event occurs when the dragged element leaves the drop target DragEvent
dragover The event occurs when the dragged element is over the drop target DragEvent
dragstart The event occurs when the user starts to drag an element DragEvent
drop The event occurs when the dragged element is dropped on the drop target DragEvent
durationchange The event occurs when the duration of the media is changed Event
ended The event occurs when the media has reach the end (useful for messages like "thanks for listening") Event
error The event occurs when an error occurs while loading an external file ProgressEventUiEventEvent
focus The event occurs when an element gets focus FocusEvent
focusin The event occurs when an element is about to get focus FocusEvent
focusout The event occurs when an element is about to lose focus FocusEvent
fullscreenchange The event occurs when an element is displayed in fullscreen mode Event
fullscreenerror The event occurs when an element can not be displayed in fullscreen mode Event
hashchange The event occurs when there has been changes to the anchor part of a URL HashChangeEvent
input The event occurs when an element gets user input InputEventEvent
invalid The event occurs when an element is invalid Event
keydown The event occurs when the user is pressing a key KeyboardEvent
keypress The event occurs when the user presses a key KeyboardEvent
keyup The event occurs when the user releases a key KeyboardEvent
load The event occurs when an object has loaded UiEventEvent
loadeddata The event occurs when media data is loaded Event
loadedmetadata The event occurs when meta data (like dimensions and duration) are loaded Event
loadstart The event occurs when the browser starts looking for the specified media ProgressEvent
message The event occurs when a message is received through the event source Event
mousedown The event occurs when the user presses a mouse button over an element MouseEvent
mouseenter The event occurs when the pointer is moved onto an element MouseEvent
mouseleave The event occurs when the pointer is moved out of an element MouseEvent
mousemove The event occurs when the pointer is moving while it is over an element MouseEvent
mouseover The event occurs when the pointer is moved onto an element, or onto one of its children MouseEvent
mouseout The event occurs when a user moves the mouse pointer out of an element, or out of one of its children MouseEvent
mouseup The event occurs when a user releases a mouse button over an element MouseEvent
mousewheel Deprecated. Use the wheel event instead WheelEvent
offline The event occurs when the browser starts to work offline Event
online The event occurs when the browser starts to work online Event
open The event occurs when a connection with the event source is opened Event
pagehide The event occurs when the user navigates away from a webpage PageTransitionEvent
pageshow The event occurs when the user navigates to a webpage PageTransitionEvent
paste The event occurs when the user pastes some content in an element ClipboardEvent
pause The event occurs when the media is paused either by the user or programmatically Event
play The event occurs when the media has been started or is no longer paused Event
playing The event occurs when the media is playing after having been paused or stopped for buffering Event
popstate The event occurs when the window's history changes PopStateEvent
progress The event occurs when the browser is in the process of getting the media data (downloading the media) Event
ratechange The event occurs when the playing speed of the media is changed Event
resize The event occurs when the document view is resized UiEventEvent
reset The event occurs when a form is reset Event
scroll The event occurs when an element's scrollbar is being scrolled UiEventEvent
search The event occurs when the user writes something in a search field (for <input="search">) Event
seeked The event occurs when the user is finished moving/skipping to a new position in the media Event
seeking The event occurs when the user starts moving/skipping to a new position in the media Event
select The event occurs after the user selects some text (for <input> and <textarea>) UiEventEvent
show The event occurs when a <menu> element is shown as a context menu Event
stalled The event occurs when the browser is trying to get media data, but data is not available Event
storage The event occurs when a Web Storage area is updated StorageEvent
submit The event occurs when a form is submitted Event
suspend The event occurs when the browser is intentionally not getting media data Event
timeupdate The event occurs when the playing position has changed (like when the user fast forwards to a different point in the media) Event
toggle The event occurs when the user opens or closes the <details> element Event
touchcancel The event occurs when the touch is interrupted TouchEvent
touchend The event occurs when a finger is removed from a touch screen TouchEvent
touchmove The event occurs when a finger is dragged across the screen TouchEvent
touchstart The event occurs when a finger is placed on a touch screen TouchEvent
transitionend The event occurs when a CSS transition has completed TransitionEvent
unload The event occurs once a page has unloaded (for <body>) UiEventEvent
volumechange The event occurs when the volume of the media has changed (includes setting the volume to "mute") Event
waiting The event occurs when the media has paused but is expected to resume (like when the media pauses to buffer more data) Event
wheel The event occurs when the mouse wheel rolls up or down over an element WheelEvent



HTML DOM Event Properties and Methods

Property/Method Description Belongs To
altKey Returns whether the "ALT" key was pressed when the mouse event was triggered MouseEvent
altKey Returns whether the "ALT" key was pressed when the key event was triggered KeyboardEventTouchEvent
animationName Returns the name of the animation AnimationEvent
bubbles Returns whether or not a specific event is a bubbling event Event
button Returns which mouse button was pressed when the mouse event was triggered MouseEvent
buttons Returns which mouse buttons were pressed when the mouse event was triggered MouseEvent
cancelable Returns whether or not an event can have its default action prevented Event
charCode Returns the Unicode character code of the key that triggered the onkeypress event KeyboardEvent
changeTouches Returns a list of all the touch objects whose state changed between the previous touch and this touch TouchEvent
clientX Returns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered MouseEventTouchEvent
clientY Returns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered MouseEventTouchEvent
clipboardData Returns an object containing the data affected by the clipboard operation ClipboardData
code Returns the code of the key that triggered the event KeyboardEvent
composed Returns whether the event is composed or not Event
createEvent() Creates a new event Event
ctrlKey Returns whether the "CTRL" key was pressed when the mouse event was triggered MouseEvent
ctrlKey Returns whether the "CTRL" key was pressed when the key event was triggered KeyboardEventTouchEvent
currentTarget Returns the element whose event listeners triggered the event Event
data Returns the inserted characters InputEvent
dataTransfer Returns an object containing the data being dragged/dropped, or inserted/deleted DragEventInputEvent
defaultPrevented Returns whether or not the preventDefault() method was called for the event Event
deltaX Returns the horizontal scroll amount of a mouse wheel (x-axis) WheelEvent
deltaY Returns the vertical scroll amount of a mouse wheel (y-axis) WheelEvent
deltaZ Returns the scroll amount of a mouse wheel for the z-axis WheelEvent
deltaMode Returns a number that represents the unit of measurements for delta values (pixels, lines or pages) WheelEvent
detail Returns a number that indicates how many times the mouse was clicked UiEvent
elapsedTime Returns the number of seconds an animation has been running AnimationEvent
elapsedTime Returns the number of seconds a transition has been running
eventPhase Returns which phase of the event flow is currently being evaluated Event
getTargetRanges() Returns an array containing target ranges that will be affected by the insertion/deletion InputEvent
getModifierState() Returns an array containing target ranges that will be affected by the insertion/deletion MouseEvent
inputType Returns the type of the change (i.e "inserting" or "deleting") InputEvent
isComposing Returns whether the state of the event is composing or not InputEventKeyboardEvent
isTrusted Returns whether or not an event is trusted Event
key Returns the key value of the key represented by the event KeyboardEvent
key Returns the key of the changed storage item StorageEvent
keyCode Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event KeyboardEvent
location Returns the location of a key on the keyboard or device KeyboardEvent
lengthComputable Returns whether the length of the progress can be computable or not ProgressEvent
loaded Returns how much work has been loaded ProgressEvent
metaKey Returns whether the "META" key was pressed when an event was triggered MouseEvent
metaKey Returns whether the "meta" key was pressed when the key event was triggered KeyboardEventTouchEvent
MovementX Returns the horizontal coordinate of the mouse pointer relative to the position of the last mousemove event MouseEvent
MovementY Returns the vertical coordinate of the mouse pointer relative to the position of the last mousemove event MouseEvent
newValue Returns the new value of the changed storage item StorageEvent
newURL Returns the URL of the document, after the hash has been changed HasChangeEvent
offsetX Returns the horizontal coordinate of the mouse pointer relative to the position of the edge of the target element MouseEvent
offsetY Returns the vertical coordinate of the mouse pointer relative to the position of the edge of the target element MouseEvent
oldValue Returns the old value of the changed storage item StorageEvent
oldURL Returns the URL of the document, before the hash was changed HasChangeEvent
onemptied The event occurs when something bad happens and the media file is suddenly unavailable (like unexpectedly disconnects)
pageX Returns the horizontal coordinate of the mouse pointer, relative to the document, when the mouse event was triggered MouseEvent
pageY Returns the vertical coordinate of the mouse pointer, relative to the document, when the mouse event was triggered MouseEvent
persisted Returns whether the webpage was cached by the browser PageTransitionEvent
preventDefault() Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur Event
propertyName Returns the name of the CSS property associated with the animation or transition AnimationEventTransitionEvent
pseudoElement Returns the name of the pseudo-element of the animation or transition AnimationEventTransitionEvent
region MouseEvent
relatedTarget Returns the element related to the element that triggered the mouse event MouseEvent
relatedTarget Returns the element related to the element that triggered the event FocusEvent
repeat Returns whether a key is being hold down repeatedly, or not KeyboardEvent
screenX Returns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggered MouseEvent
screenY Returns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggered MouseEvent
shiftKey Returns whether the "SHIFT" key was pressed when an event was triggered MouseEvent
shiftKey Returns whether the "SHIFT" key was pressed when the key event was triggered KeyboardEventTouchEvent
state Returns an object containing a copy of the history entries PopStateEvent
stopImmediatePropagation() Prevents other listeners of the same event from being called Event
stopPropagation() Prevents further propagation of an event during event flow Event
storageArea Returns an object representing the affected storage object StorageEvent
target Returns the element that triggered the event Event
targetTouches Returns a list of all the touch objects that are in contact with the surface and where the touchstart event occured on the same target element as the current target element TouchEvent
timeStamp Returns the time (in milliseconds relative to the epoch) at which the event was created Event
total Returns the total amount of work that will be loaded ProgressEvent
touches Returns a list of all the touch objects that are currently in contact with the surface TouchEvent
transitionend The event occurs when a CSS transition has completed TransitionEvent
type Returns the name of the event Event
url Returns the URL of the changed item's document StorageEvent
which Returns which mouse button was pressed when the mouse event was triggered MouseEvent
which Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event KeyboardEvent
view Returns a reference to the Window object where the event occurred UiEvent