戻る

<a href="#">のclickイベントで、上に移動させない方法
<a href="#">のclickイベントが実行されると、画面が上にスクロールしてしまう現象をjavascriptで制御する方法
画面がスクロールしないと見れない位置に<a href>タグを使用してケースがあります。
この<a href>タグをボタン代わりに使用している場合、リンクをクリックすると画面が上にスクロールしてしまう現象が発生します。
通常であれば、リンクボタンをクリックしても、画面位置を固定したいケースが多いと思うため、その制御をjavascriptで実装するための方法となります。

hrefにvoid(0)を実装する方法
<a href="javascript:void(0);" id=href1>テスト</a>
<script>
document.getElementById("href1").addEventListener("click", function(event){
	alert("void(0)を使ったテスト");
}, false);
</script>

event.preventDefault()メソッドを使った方法
リンクの遷移機能の動作を制限するメソッドです。
<a href="#" id=href2>テスト</a>
<script>
document.getElementById("href2").addEventListener("click", function(event){
	event.preventDefault();
	alert("event.preventDefault()メソッドを使ったを使ったテスト");
}, false);
</script>


戻る
back

How to prevent <a href="#"> tag from moving up with a click event
How to use Javascript to control the phenomenon where the screen scrolls up when the click event of the <a href="#">tag is execute.
There are cases where the <a href> tag is used in a position that cannnot be seen without scrolling the screen.
If this <a href> tag is used in place of a button,
the screen will scroll up when you click the link.
Normarlly, there are many cases where you want the screen position to be fixed even when you click <a href> link button,
so this is a way to implement that control using Javascript.
How to implement void(0) in href
<a href="javascript:void(0);" id=href1">test</a>
<scrip>
document.getElementById("href1").addEventListener("click", function(event){
	alert("Testing with void(0)");
}, false);
</script>

Method using event.preventDefault() method
This method restricts the operation of the link transition function.
<a href="#" id=href2>test</a>
<script>
document.getElementById("href2").addEventListener("click", function(event){
	event.preventDefault();
	alert("Test using event.preventDefault() method");
}, false);
</script>


back



著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。