LoginSignup
0
0

More than 3 years have passed since last update.

マウスをのせた時にツールチップを表示する~jQuery無し~

Last updated at Posted at 2021-05-28

マウスをのせた時にツールチップを表示する~jQuery無し~

指定の要素にマウスをのせた時に、ツールチップを表示するJavaScriptを作成しました。

動作のイメージは、次の図のような感じです。「こちらが2個目です」の文字に

マウスを乗せると、赤い背景の「2個目です。」が表示されます。

※「2個目」と「です」で改行されています。

image.png

javascript
const att_elem_id = 'msg_elem_id';
const att_msg = 'msg';
class tooltips {
    constructor(elm, msg) {
        elm.onmouseover = function () { showPopup(this, event); }
        elm.onmouseout = function () { hidePopup(this, event); }
        elm.setAttribute(att_elem_id, elm.id);
        elm.setAttribute(att_msg, msg);
    }
}
function showPopup(e, event) {
    let id = e.getAttribute(att_elem_id);
    let el = document.getElementById(id);
    if (el != null && id != null && id != '') {
        let msg = el.getAttribute(att_msg);
        if (msg != null && msg != '') {
            el = document.getElementById('tooltip');
            el.innerHTML = msg;
            el.style.display = 'inline-block';

            let x = event.clientX + window.scrollX + 8;
            let y = event.clientY + window.scrollY + 8;
            el.style.left = x + 'px';
            el.style.top = y + 'px';
        }
    }
    el = null;
}
function hidePopup(e) {
    let el = document.getElementById('tooltip');
    if (el != null) { el.style.display = 'none'; }
    el = null;
}
function windowScroll() { hidePopup(null); }

window.onload = function () {
  new tooltips(document.getElementById('inp01'), '1個目');
  new tooltips(document.getElementById('inp02'), '2個目<br>です。');
}

また、要素自体は次のように指定して下さい。

html

<div id="tooltip" style="background-color: red; color: white; display: none; position: absolute; z-index: 88888; width: fit-content;"></div>

<a id="inp01">こちらが1個目です</a>

<br /><br /><br />

<a id="inp02">こちらが2個目です</a>

javascriptのonloadイベントの中で、

new tooltips([[要素名]] , [[表示するメッセージ]]);

と指定するだけです。

ツールチップの書式は、自分のお好みに合わせて下さい。

jQuery無しでも簡単にできますし、ベースを自分で作った方がカスタマイズが非常に楽です。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0