javascript onselectでテキストの選択イベントを取得する
- 作成日 2021.01.02
- 更新日 2022.08.01
- javascript
- javascript

javascriptで、onselectを使用してテキストの選択イベントを取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 103.0.5060.134
onselect使い方
onselectを使用すると、テキストの選択イベントを取得することが可能です。
/* html内で利用 */
<タグ onselect ="イベント">
/* js内で利用 */
object.onselect = function(){ イベント };
onselect使い方(html内での使用例)
<div style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<input onselect="hoge()" type="text" value="mebee" />
</div>
<script>
'use strict';
function hoge(){
console.log('選択されました');
};
</script>
onselect使い方(js内での使用例)
<div style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<input id="main" type="text" value="mebee" />
</div>
<script>
'use strict';
document.getElementById('main').onselect = function(){
console.log('選択されました');
};
</script>
実行結果をみると、テキストを選択時に、コンソールに「選択されました」と表示されます。

macのsafari(13.1.1)では、マウスで複数文字を選択すると、1文字ごとの選択でイベント発生する挙動になりました。全選択時は、1回のイベントとなります。

また、以下のコードを、
document.getElementById('main').onselect = function(){
console.log('選択されました');
};
document.getElementByIdの省略と関数をアロー化して、簡潔に記述することもできます。
main.onselect = () => {
console.log('選択されました');
};
addEventListener
addEventListenerに登録しても、同じ結果となります。
document.getElementById("main").addEventListener (
"select", function(){ console.log('選択されました') }
)
サンプルコード
以下は、
テキストフォーム内で文字列の選択を検知すると、カウントして、カウントした数を表示する
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
let count = 0;
const hoge = () => {
count++;
result.innerHTML = `選択された回数${count}`;
}
window.onload = () => {
sample.onselect = () => { hoge(); };
}
</script>
<body>
<div class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<p id="result" class="bg-purple-500 text-white py-2 px-8 rounded-full mb-3 mt-4">カウント</p>
</div>
<div class="flex justify-center">
<input id="sample" type="text"
value="mebee" class="shadow appearance-none border border-purple-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline">
</div>
</div>
</body>
</html>
選択した回数がカウントされていることが確認できます。

-
前の記事
Ruby 全てが同じ値の多次元配列を作成する 2021.01.01
-
次の記事
rails6 APIから取得したデータでseedを実行する 2021.01.02
コメントを書く