javascript onselectでテキストの選択イベントを取得する
- 2021.01.02
- javascript
- javascript

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

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

また、以下のコードを、
1 2 3 |
document.getElementById('main').onselect = function(){ console.log('選択されました'); }; |
document.getElementByIdの省略と関数をアロー化して、簡潔に記述することもできます。
1 2 3 |
main.onselect = () => { console.log('選択されました'); }; |
サンプルコード
以下は、
テキストフォーム内で文字列の選択を検知すると、カウントして、カウントした数を表示する
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<!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
コメントを書く