画面遷移の実装方法 - JavaScriptでページ移動する基本テクニック

JavaScriptを使った画面遷移の実装方法を初心者向けに解説。location.hrefやhistory.pushStateなど基本的な手法から実践的な活用例まで詳しく説明します。

Learning Next 運営
27 分で読めます

みなさん、Webサイトを作っていて困ったことはありませんか?

「ボタンをクリックしたら他のページに移動したい」「条件によって違うページに案内したい」

こんな要求は、Web開発でとてもよくあることですよね。 実は、JavaScriptを使うことで簡単にページ間の移動を実現できるんです。

この記事では、JavaScriptを使った画面遷移の実装方法を初心者向けに分かりやすく解説します。 基本的な手法から実践的な活用例まで、一緒に学んでいきましょう!

画面遷移って何?基本を理解しよう

画面遷移の正体

画面遷移とは、ユーザーを異なるページやURLに移動させる処理のことです。

簡単に言うと、「今いるページから別のページに移動する」機能なんです。 これにより、ユーザーの操作に応じて適切なページへ案内できます。

例えば、こんな場面で使われます。

  • ログインボタンを押したらログインページへ移動
  • 商品をクリックしたら詳細ページへ移動
  • フォーム送信後に完了ページへ移動

どんな移動方法があるの?

JavaScriptで実現できる画面遷移には、主にこんな種類があります。

  • location.href: 最も基本的なページ移動
  • location.assign(): hrefと同じような機能
  • location.replace(): 履歴を残さないページ移動
  • window.open(): 新しいウィンドウ・タブでページを開く
  • history.pushState(): SPAでの画面遷移

それぞれに特徴があるので、用途に応じて使い分けることが大切です。

location.hrefを使った基本的なページ移動

一番シンプルな方法

location.hrefは最も一般的で分かりやすいページ移動の方法です。

// 基本的な使い方
function navigateToPage() {
location.href = 'https://example.com';
}
// 相対パスでの移動
function goToAboutPage() {
location.href = '/about';
}
// 現在のディレクトリからの移動
function goToContactPage() {
location.href = 'contact.html';
}

この方法は直感的で、初心者の方にもおすすめです。

HTMLボタンと組み合わせてみよう

実際のHTMLボタンと組み合わせた例を見てみましょう。

<!DOCTYPE html>
<html>
<head>
<title>画面遷移サンプル</title>
</head>
<body>
<h1>メインページ</h1>
<button onclick="goToHome()">ホームページへ</button>
<button onclick="goToProducts()">商品一覧へ</button>
<button onclick="goToContact()">お問い合わせへ</button>
<script>
function goToHome() {
location.href = '/';
}
function goToProducts() {
location.href = '/products';
}
function goToContact() {
location.href = '/contact';
}
</script>
</body>
</html>

ボタンをクリックするだけで、簡単にページ移動ができますね。

URLパラメータも一緒に送ろう

検索キーワードやユーザーIDなどの情報も一緒に送れます。

function searchProducts(keyword) {
location.href = `/search?q=${encodeURIComponent(keyword)}`;
}
function showUserProfile(userId) {
location.href = `/user/profile?id=${userId}`;
}
function filterByCategory(category) {
const currentUrl = new URL(location.href);
currentUrl.searchParams.set('category', category);
location.href = currentUrl.toString();
}
// 使用例
searchProducts('JavaScript'); // /search?q=JavaScript
showUserProfile(123); // /user/profile?id=123
filterByCategory('electronics'); // 現在のURLにcategory=electronicsを追加

この方法で、動的な情報をページ間で受け渡しできます。

履歴を残すか残さないかの使い分け

location.assign()の使い方

**location.assign()**はlocation.hrefとほぼ同じ動作をします。

// location.hrefと同じ動作
function navigateWithAssign() {
location.assign('https://example.com');
}
// 履歴に残る移動
function goToPageWithHistory() {
location.assign('/new-page');
// ブラウザの「戻る」ボタンで元のページに戻れる
}

この方法では、ブラウザの履歴に移動記録が残ります。

location.replace()の使い方

**location.replace()**は履歴を残さずにページ移動します。

// 履歴を残さない移動
function navigateWithReplace() {
location.replace('https://example.com');
// ブラウザの「戻る」ボタンでは元のページに戻れない
}
// ログイン後のリダイレクト
function redirectAfterLogin() {
// ログインページを履歴から削除してダッシュボードへ
location.replace('/dashboard');
}

この方法は、ユーザーに戻って欲しくないページからの移動で使います。

どんな時にどれを使う?

適切な使い分けの例を見てみましょう。

// ログイン処理
function handleLogin(username, password) {
if (authenticate(username, password)) {
// ログイン成功:ログインページを履歴から削除
location.replace('/dashboard');
} else {
// ログイン失敗:同じページに留まる
alert('ログインに失敗しました');
}
}
// ページ閲覧
function viewArticle(articleId) {
// 通常のページ移動:履歴に残す
location.assign(`/article/${articleId}`);
}
// エラーページからのリダイレクト
function handleError() {
// エラーページを履歴から削除してホームへ
location.replace('/');
}

このように、状況に応じて適切な方法を選ぶことが大切です。

条件によってページを切り替えよう

ユーザーの選択に応じた移動

ユーザーの選択や入力に応じてページを切り替える例です。

<select id="page-selector" onchange="navigateBySelection()">
<option value="">ページを選択</option>
<option value="home">ホーム</option>
<option value="about">会社概要</option>
<option value="services">サービス</option>
<option value="contact">お問い合わせ</option>
</select>
<script>
function navigateBySelection() {
const selector = document.getElementById('page-selector');
const selectedValue = selector.value;
if (selectedValue) {
location.href = `/${selectedValue}`;
}
}
</script>

セレクトボックスから選んだページに移動できます。

ログイン状態による切り替え

ユーザーがログインしているかどうかで移動先を変える方法です。

function checkAuthAndNavigate(targetPage) {
const isLoggedIn = checkLoginStatus();
if (isLoggedIn) {
// ログイン済み:目的のページへ
location.href = targetPage;
} else {
// 未ログイン:ログインページへリダイレクト
const returnUrl = encodeURIComponent(targetPage);
location.href = `/login?return=${returnUrl}`;
}
}
function checkLoginStatus() {
// 実際の実装ではサーバーとの通信や
// ローカルストレージの確認などを行う
return localStorage.getItem('authToken') !== null;
}
// 使用例
function goToProfile() {
checkAuthAndNavigate('/profile');
}
function goToSettings() {
checkAuthAndNavigate('/settings');
}

この方法で、認証が必要なページへの安全なアクセスを実現できます。

フォーム送信後の移動

フォームの送信結果に応じてページを切り替える例です。

<form id="contact-form" onsubmit="handleFormSubmit(event)">
<input type="text" name="name" placeholder="お名前" required>
<input type="email" name="email" placeholder="メールアドレス" required>
<textarea name="message" placeholder="メッセージ" required></textarea>
<button type="submit">送信</button>
</form>
<script>
async function handleFormSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
try {
const response = await fetch('/api/contact', {
method: 'POST',
body: formData
});
if (response.ok) {
// 送信成功:成功ページへ
location.href = '/contact/success';
} else {
// 送信失敗:エラーページへ
location.href = '/contact/error';
}
} catch (error) {
// ネットワークエラー:エラーページへ
console.error('送信エラー:', error);
location.href = '/contact/error';
}
}
</script>

フォームの処理結果に応じて、適切なページに案内できます。

新しいタブやウィンドウで開こう

新しいタブでページを開く

外部リンクや補助的なページを新しいタブで開く方法です。

// 新しいタブでページを開く
function openInNewTab(url) {
window.open(url, '_blank');
}
// 新しいウィンドウで開く(サイズ指定)
function openInNewWindow(url) {
window.open(
url,
'newWindow',
'width=800,height=600,scrollbars=yes,resizable=yes'
);
}
// ポップアップウィンドウ
function openPopup(url) {
window.open(
url,
'popup',
'width=400,height=300,left=100,top=100,scrollbars=no,toolbar=no,menubar=no'
);
}

用途に応じて、新しいタブやポップアップを使い分けましょう。

外部リンクを安全に処理しよう

外部サイトへのリンクを安全に処理する方法です。

function openExternalLink(url) {
// セキュリティ対策:rel="noopener noreferrer"と同等の効果
const newWindow = window.open(url, '_blank');
newWindow.opener = null;
}
// 確認ダイアログ付きの外部リンク
function openExternalLinkWithConfirm(url) {
const confirmed = confirm('外部サイトに移動します。よろしいですか?');
if (confirmed) {
openExternalLink(url);
}
}
// 使用例
function linkToGitHub() {
openExternalLinkWithConfirm('https://github.com');
}

この方法で、ユーザーに確認を取りながら安全に外部サイトに案内できます。

時間差でページを移動しよう

自動的にページを移動する

一定時間後に自動的にページ移動する機能です。

// 指定秒後に自動遷移
function redirectAfterDelay(url, seconds) {
console.log(`${seconds}秒後に${url}へ移動します`);
setTimeout(() => {
location.href = url;
}, seconds * 1000);
}
// カウントダウン表示付きの自動遷移
function redirectWithCountdown(url, seconds) {
const countdownElement = document.getElementById('countdown');
let remainingTime = seconds;
const updateCountdown = () => {
countdownElement.textContent = `${remainingTime}秒後に移動します...`;
if (remainingTime <= 0) {
location.href = url;
} else {
remainingTime--;
setTimeout(updateCountdown, 1000);
}
};
updateCountdown();
}
// 使用例
function showSuccessAndRedirect() {
alert('登録が完了しました!');
redirectWithCountdown('/dashboard', 5);
}

この方法で、ユーザーにメッセージを表示してから移動できます。

プログレスバー付きの移動

視覚的なフィードバックを含む画面遷移の例です。

<div id="loading-overlay" style="display: none;">
<div class="loading-content">
<h3>ページを読み込んでいます...</h3>
<div class="progress-bar">
<div id="progress" class="progress-fill"></div>
</div>
</div>
</div>
<style>
#loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
}
.loading-content {
background: white;
padding: 20px;
border-radius: 8px;
text-align: center;
}
.progress-bar {
width: 300px;
height: 20px;
background-color: #f0f0f0;
border-radius: 10px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background-color: #007bff;
width: 0%;
transition: width 0.3s ease;
}
</style>
<script>
function navigateWithProgress(url) {
const overlay = document.getElementById('loading-overlay');
const progress = document.getElementById('progress');
overlay.style.display = 'flex';
let progressValue = 0;
const progressInterval = setInterval(() => {
progressValue += 10;
progress.style.width = progressValue + '%';
if (progressValue >= 100) {
clearInterval(progressInterval);
setTimeout(() => {
location.href = url;
}, 500);
}
}, 100);
}
</script>

この方法で、ユーザーに「読み込み中」であることを分かりやすく伝えられます。

フォームの検証と組み合わせよう

入力内容をチェックしてから移動

フォームの入力内容を検証してから画面遷移する例です。

<form id="registration-form">
<input type="text" id="username" placeholder="ユーザー名" required>
<input type="email" id="email" placeholder="メールアドレス" required>
<input type="password" id="password" placeholder="パスワード" required>
<button type="submit">登録</button>
</form>
<script>
document.getElementById('registration-form').addEventListener('submit', function(event) {
event.preventDefault();
const username = document.getElementById('username').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
// バリデーション
const validationResult = validateForm(username, email, password);
if (validationResult.isValid) {
// バリデーション成功:登録処理後に画面遷移
performRegistration(username, email, password)
.then(() => {
location.href = '/registration/success';
})
.catch((error) => {
alert('登録に失敗しました: ' + error.message);
});
} else {
// バリデーション失敗:エラーメッセージ表示
alert('入力エラー: ' + validationResult.errors.join(', '));
}
});
function validateForm(username, email, password) {
const errors = [];
if (username.length < 3) {
errors.push('ユーザー名は3文字以上で入力してください');
}
if (!email.includes('@')) {
errors.push('正しいメールアドレスを入力してください');
}
if (password.length < 8) {
errors.push('パスワードは8文字以上で入力してください');
}
return {
isValid: errors.length === 0,
errors: errors
};
}
async function performRegistration(username, email, password) {
// 実際の登録処理(API呼び出しなど)
const response = await fetch('/api/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, email, password })
});
if (!response.ok) {
throw new Error('サーバーエラーが発生しました');
}
return response.json();
}
</script>

この方法で、無効な入力による無駄な画面遷移を防げます。

エラーが起きた時の対策

安全なページ移動の実装

画面遷移が失敗した場合の対応方法です。

function safeNavigate(url, options = {}) {
try {
// URLの妥当性チェック
new URL(url, location.origin);
// オプションに応じた遷移方法の選択
if (options.newTab) {
window.open(url, '_blank');
} else if (options.replace) {
location.replace(url);
} else {
location.href = url;
}
} catch (error) {
console.error('画面遷移エラー:', error);
// フォールバック処理
if (options.fallbackUrl) {
location.href = options.fallbackUrl;
} else {
alert('ページの移動に失敗しました。');
}
}
}
// ネットワーク状態を考慮した遷移
function navigateWithNetworkCheck(url) {
if (navigator.onLine) {
location.href = url;
} else {
alert('インターネット接続を確認してください。');
// オフライン用ページへの遷移
location.href = '/offline';
}
}
// 使用例
function handleNavigationClick(url) {
safeNavigate(url, {
fallbackUrl: '/',
replace: false
});
}

この方法で、エラーが発生してもユーザーを適切にガイドできます。

まとめ

JavaScriptを使った画面遷移は、ユーザー体験を向上させる重要な技術です。

重要なポイントをおさらいしましょう。

  • location.href: 最も基本的で分かりやすいページ移動
  • location.replace(): 履歴を残さない移動(ログイン後など)
  • window.open(): 新しいタブやウィンドウでページを開く
  • 条件付き遷移: ユーザーの状態に応じた適切な案内
  • 時間差移動: カウントダウンやプログレスバーでUX向上

実践で役立つテクニックも身につきました。

  • フォーム検証との組み合わせ
  • 認証状態による移動先の切り替え
  • エラーハンドリングとフォールバック処理
  • 視覚的フィードバックの提供

適切な画面遷移の実装により、ユーザーがスムーズにサイト内を移動できる環境を作ることができます。 特に、ユーザーの意図と状況に応じた適切な遷移方法の選択が重要です。

ぜひこれらの技術をマスターして、より使いやすいWebアプリケーションを作成してみてくださいね!

関連記事