トップページに戻る
Javascriptプログラム例
このページでは、特にWebで使われる フロントサイド
Javascript でよく使われるプログラム例を掲載しています。
読み込み
- HTML内でのJavascriptファイル script.js の読み込み:
<script src="script.js"></script>
(<head>でも<body>でもよい)
- HTML内での Javascript の記述:
<script>
// ここに Javascript文
</script>
window.addEventListener
ブラウザウィンドウ全体に関するイベント
window.addEventListener(event, function() {
..;
});
- event = 'load':
画像やスタイルシート、スクリプトなどのリソースを含め、ページ全体が完全に読み込まれたときに実行
- event = 'unload': ページがアンロードされるとき
- event = 'scroll': 要素をスクロールしたときに実行
- event = 'resize': ウインドウサイズが変更されたとき
document.addEventListener
ページ全体のDOMに関連するイベント
document.addEventListener(event, function() {
..;
});
-
event = 'DOMContentLoaded': HTMLドキュメントの構造が完全に読み込まれたときに実行。
画像やスタイルシートが全て読み込まれるのは待たない。
-
event = 'click': ボタンやリンクなどがクリックされたとき
- event = 'focus': 要素がフォーカスされたとき
- event = 'blur': フォーカスが外れた時
- event = 'input': 入力フィールドの内容を変更したとき
- event = 'change': 入力フィールドやリストの選択が変更されたとき
- event = 'submit': フォームが送信されたとき
- event = 'keyup': キーが離されたとき
- event = 'keydown': キーが押されたとき
- event = 'mouseover': マウスカーソルが乗ったとき
- event = 'mouseout': マウスカーソルが離れたとき
- dragover
- dragleave
- drop
Debug
- 開発者ツールにログを出力
console.log(message);
onerror: エラーが発生したときにcallbackを呼び出す
- <script src="nonexistent.js" onerror="console.error('Failed to load script.');"></script>
- <img src="nonexistent.jpg" alt="Image" onerror="this.src='placeholder.jpg'; this.alt='Placeholder Image';">
- window.onerror = function(message, source, lineno, colno, error) {
console.error(`Error: ${message} at ${source}:${lineno}:${colno}`);
// エラーログの送信やUIの更新など、追加のエラーハンドリング処理を行う
};
// 意図的にエラーを発生させてみる
function throwError() {
throw new Error('Something went wrong!');
}
throwError();
- window.onerror = function(message, source, lineno, colno, error) {
displayError(`Error: ${message} at ${source}:${lineno}:${colno}`, '');
return true; // ブラウザのコンソールにエラーを表示しないようにします
};
function handleError(resource, selector = '') {
displayError(`Failed to load resource: ${resource}`, selector);
}
function displayError(errorMsg, selector = '') {
let targetElement;
if (selector) {
targetElement = document.querySelector(selector);
if (targetElement === null) {
alert(`Error in displayError: Invalid selector ${selector}`);
}
} else {
targetElement = document.body;
}
const errorDiv = document.createElement('div');
errorDiv.style.color = 'red'; // エラーメッセージを目立たせるために赤色に設定
const errorParagraph = document.createElement('span');
errorParagraph.innerHTML += errorMsg + "<br>";
errorDiv.appendChild(errorParagraph);
targetElement.appendChild(errorDiv);
}
正規表現による置換: HTMLタグの無効化
- function escapeHTML(html) {
return html.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
Template文字列の置換: ファイル名の置換
- function processTemplate(basePath, strTemplate) {
const dirPath = basePath.substring(0, basePath.lastIndexOf("/")); // ディレクトリパス
const fileName = basePath.substring(basePath.lastIndexOf("/") + 1); // ファイル名
const extension = fileName.substring(fileName.lastIndexOf(".") + 1); // 拡張子
const fileBody = fileName.substring(0, fileName.lastIndexOf(".")); // ファイル本体(拡張子除去)
const result = strTemplate
.replace("{{dirPath}}", dirPath)
.replace("{{fileBody}}", fileBody)
.replace("{{extension}}", extension)
.replace("{{fileName}}", fileName);
return result;
}
未定義変数の確認
- 未定義かどうかの確認
if (typeof myVar === "undefined")
- 無効値 (undefined || null || "")
if (myVar === undefined || myVar === null || myVar === "")
- オブジェクトの要素が未定義の場合に初期値を設定
const { name = "default" } = objectVar;
Selectorから 頭の . あるいは # を削除
- removeSelectorHeading:function(selector) {
if (selector.startsWith('#') || selector.startsWith('.')) {
return selector.substring(1);
}
return selector;
}
SelectorあるいはElementオブジェクトを受け取る関数
- function getElement(newElement = '') {
if (typeof newElement === 'string') {
newElement = removeSelectorHeading(newElement);
// selector == ""なら<body>を返す
if (newElement === '') {
return document.body;
}
// selector != ""
なら<span>要素に文字列を入れて返す
const element = document.createElement("span");
element.innerHTML = newElement;
return element;
} else if (newElement instanceof Element) {
// Elementオブジェクトならそのまま返す
return newElement;
}
return null;
}
同期してファイルを取得
- async function fetchContent(url, rettype = "text") {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const extension = url.split('.').pop().toLowerCase();
if (rettype === 'buffer' || extension === 'xlsx' || ext === 'xlsm') {
return await response.arrayBuffer();
} else {
return await response.text();
}
} catch (error) {
return null;
}
}
XMLファイルを取得してパース: 非同期関数 (async)
で終了待ち (await)
- async function App.fetchAndParseXML(url) {
const response = await fetch(url);
const text = await response.text();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(text, "text/xml");
return xmlDoc;
}
UTF8へ変換
- function convertToUTF8(buffer) {
if (typeof buffer === 'string') {
const encoder = new TextEncoder();
uint8Array = encoder.encode(buffer); // 文字列をエンコードして Uint8Array に変換
} else if (buffer instanceof ArrayBuffer) {
uint8Array = new Uint8Array(buffer); // 既に ArrayBuffer の場合はそのまま Uint8Array に変換
}
if (typeof Encoding === 'undefined') {
return uint8Array;
}
// 文字コードを判別
const encoding = Encoding.detect(uint8Array);
const utf8Array = Encoding.convert(uint8Array, 'UTF8', encoding);
return new Uint8Array(utf8Array);
}
DOM取得
- <div id="id_string"></div>
var elements = document.getElementById('id_string');
- <div class="class_string"></div>
var elements = document.getElementsByClassName('class_string');
- var element = document.querySelector('.class_string');
var element = document.querySelector('#id_string');
- var elements = document.querySelectorAll('.class_string');
var elements = document.querySelectorAll('#id_string');
- var elements = document.getElementsByTagName('div');
- <input type="text" name="username" />
<select name="country">
<option ...>..</option>
</select>
var elements = document.getElementsByName('username');
- const element = document.getElementById(id);
if (element.classList.contains('hidden')) {
element.classList.remove('hidden');
} else {
element.classList.add('hidden');
}
- <body>の内容を取得
document.body
あるいは
const parser = new DOMParser();
const doc = parser.parseFromString(text, 'text/html');
const bodyContent = doc.body.innerHTML;
DOM作成
- const style = document.createElement('style');
style.textContent = `
#gallery {
display: flex;
flex-wrap: wrap;
}
.gallery-item {
margin: 5px;
}
.gallery-item img {
width: 100%;
}
`;
document.head.appendChild(style);
- const galleryItem = document.createElement('div');
galleryItem.classList.add('gallery-item');
galleryItem.style.width = `${100 / ncolumn}%`;
const img = document.createElement('img');
img.src = `${url_dir}${file}`;
img.style.width = `${width}px`;
img.alt = file;
img.onclick = () => {
window.open(img.src, '_blank', 'width=800,height=600');
};
const caption = document.createElement('p');
caption.innerText = file;
galleryItem.appendChild(img);
galleryItem.appendChild(caption);
gallery.appendChild(galleryItem);
const eventDiv = document.createElement('div');
eventDiv.classList.add('event');
eventDiv.setAttribute('data-year', keywordList.join('|'));
DOM操作
- 要素を不可視にしたり可視にしたりする
const events = document.querySelectorAll('.event');
events.forEach(event => {
if (year === '全て' || event.getAttribute('data-year').includes(year)) {
event.style.display = 'block';
} else {
event.style.display = 'none';
}
});
DOMの追加
- elementの最後に追加:
element.appendChild(content);
- referenceElementの前に追加:
parent.insertBefore(newElement, referenceElement);
- 指定した位置に挿入:
element.insertAdjacentHTML('beforeend', '<p>New paragraph</p>');
// オプション: 'beforebegin', 'afterbegin', 'beforeend', 'afterend'
- parentの最初の子要素として挿入:
parent.prepend(newElement);
- parentの最後の雇用素として追加:
parent.append(newElement);
- 既存の子要素を置換:
parent.replaceChild(newElement, oldElement);
- div.innerHTML = str;
- div.outerHTML = str;
- div.textContent = str;
新しいURLを開く
新しいウインドウでURLを開く
- const url = "https://example.com"; // 開きたいURL
const windowName = "_blank"; //
新しいウィンドウで開く指定
const features = "width=800,height=600"; //
ウィンドウサイズ等の指定(オプション)
window.open(url, windowName, features);
新しいウインドウを開く関数
- function showFullHtmlInNewWindow() {
const fullHtml = document.documentElement.outerHTML;
const escapedHtml = escapeHtml(fullHtml);
const newWindow = window.open("", "_blank", "width=800,height=600");
if (newWindow) {
newWindow.document.open();
newWindow.document.write(`
<html>
<head>
<title>Full HTML</title>
</head>
<body>
<pre style="white-space: pre-wrap;">${escapedHtml}</pre>
</body>
</html>
`);
newWindow.document.close();
} else {
alert("Pop-up blocked! Please allow pop-ups for this website.");
}
}
クリップボードへコピー
- function copyToClipboard(dialogMessage, copyTextId) {
const textElement = document.getElementById(copyTextId);
const text = textElement.innerText || textElement.textContent;
const textarea = document.createElement("textarea");
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
showModal("copied to clipboard");
}
<head>へのstyleの挿入
- function insertCSS() {
const style = document.createElement('style');
style.textContent = `
.dropdown-content {
display: none;
position: absolute;
}`;
document.head.appendChild(style);
}
関数
- 非同期関数の定義: async
非同期関数の終了を待つ: await
async function fetchData(url) {
try {
const response = await fetch(url); // データを取得
const data = await response.json(); // JSON形式に変換
console.log(data); // データをコンソールに表示
} catch (error) {
console.error('Error fetching data:', error);
}
}
- 複数の非同期リクエストを連続して行う
async function fetchMultipleData() {
try {
const [response1, response2] = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]);
const data1 = await response1.json();
const data2 = await response2.json();
console.log('Data 1:', data1);
console.log('Data 2:', data2);
} catch (error) {
console.error('Error fetching data:', error);
}
}
- ファイル内容取得
async function loadData(file) {
const response = await fetch(file);
return await response.text();
}
Promize
- const loadPage = (pageUrl) => {
fetch(pageUrl)
.then(response => response.text())
.then(html => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
tabContent.innerHTML = doc.body.innerHTML;
document.title = doc.title; // Webブラウザのタイトルを設定
})
.catch(error => console.error('Error loading page:', error));
};
History
- history.pushState({ page: target }, '', `?page=${target}`);
- history.replaceState({ page: initialPage }, '', `?page=${initialPage}`);
documentの属性
- document.head
- document.body
- document.title
windowの属性
- window.document
- window.innerWidth
- window.innerHeight
- window.outerWidth
- window.outerHeight
- window.location // url
- window.history
- window.navigator // ブラウザ
navigator.userAgent
- window.screen // ディスプレイ
screen.width,screen.height
- window.localStorage
- window.sessionStorage
- window.alert(), window.confirm(), window.prompt()
- window.innerWidth
- window.innerHeight
現在のURLを取得
window.location.href