意外とやりがちな、JavaScriptでページ遷移できない書き方と対処
研修生から相談のあった書き方をメモしておきます。
formにボタンを作り、選んだボタンによって違うページに遷移したいケースを想定しています。
consoleのエラーですぐわかる記述ミス
consoleに「Uncaught TypeError: Cannot read property 〜」と出る場合。
JavaScript読み込みの順番によっては、そもそも要素を取得できません。
htmlに要素を記述した後にJavaScriptを読み込む対処方法のほか、
要素を取得するJavaScript記述をload完了後に動くよう手を加える、といった対処方法があります。
要素の後に読み込む対処例
<form action="index.html" name="sample"> <input type="submit" name="button1" value="ボタン1"> <input type="submit" name="button2" value="ボタン2"> <button type="button" name="button3">ボタン3</button> </form> <script src="main.js"></script> /* JSを後から読み込む */
htmlのload後に要素を取得する対処例
window.onload =()=> { // 要素を取得するコードを記述 }
ボタンがsubmitになっていて、formのactionで動いてしまう書き方
formの子要素のボタンがsubmitになっている場合、clickイベントとlocation.hrefだけでは遷移しません。
<form name="sample"> <input type="submit" name="button1" value="ボタン1"> </form>
// 動かない const button1 = document.forms.sample.button1; button1.addEventListener('click', ()=>{ location.href = 'top.html'; });
<input type=submit>
のまま動かしたい場合は、click後にイベントを停止します。
イベントを停止してページ遷移する対処例
<form name="sample"> <input type="submit" name="button2" value="ボタン2"> </form>
// イベントを無効化すればsubmitでも動く const button2 = document.forms.sample.button2; button2.addEventListener('click', (e)=>{ e.preventDefault(); location.href = 'top.html'; });
inputタグではなくbuttonで実装する対処例
<form name="sample"> <button type="button" name="button3">ボタン3</button> </form>
// submitじゃなくてbuttonにする const button3 = document.forms.sample.button3; button3.addEventListener('click', ()=>{ location.href = 'top.html'; });
レスポンシブ対応の共通cssのfont-sizeメモ
レスポンシブ対応のサイトにするときのfont-size関連の書き方。
html に基本の倍率を10px として設定し、bodyで全体を14や16pxになるようにします。 この場合は1.4remで14px (ついでによく使うfont-familyとline-heightもメモ)
html { font-size: 62.5%; /* 10px */ } body { font-family: Quicksand, 游ゴシック体, "Yu Gothic", YuGothic, "ヒラギノ角ゴシック Pro", "Hiragino Kaku Gothic Pro", メイリオ, Meiryo, Osaka, "MS Pゴシック", "MS PGothic", sans-serif; line-height: 2; font-size: 1.4em; /* 14px */ }
スマホなどはメディアクエリで対応します。 (ブレイクポイントはbootstrap4を参考にしてるけどこれも諸説あり)
@media (max-width: 576px) { body { font-size: 1.5em; /* スマホは15px */ } }
モダンブラウザ向けリセットCSS
こちらの記事を参考に、よく使うCSSを残しておきます。
/* https://coliss.com/articles/build-websites/operation/css/a-modern-css-reset.html */ *, *::before, *::after { box-sizing: border-box; } ul[class], ol[class] { padding: 0; } ul[class] { list-style-type: none; } body, h1, h2, h3, h4, h5, p, ul[class], ol[class], li, figure, figcaption, blockquote, dl, dd { margin: 0; } body { min-height: 100vh; scroll-behavior: smooth; text-rendering: optimizeSpeed; line-height: 1.5; } ul[class], ol[class] { list-style: none; } a:not([class]) { text-decoration-skip-ink: auto; } img { max-width: 100%; display: block; } article > * + * { margin-top: 1em; } input, button, textarea, select { font: inherit; } @media (prefers-reduced-motion: reduce) { * { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; } }