• 회원가입
  • 로그인
  • 구글아이디로 로그인

[js] JS - 이미지 위에 마우스허버 시 툴팁창(Tooltip) 띄우기 ※ 클래스 속성값과 동일한 타이틀 속성 생성 ※ 여러 이벤트에 동일 실행코드 적용

목차

  1. title 속성 생성 방법
  2. tooltip 요소 생성 방법
  3. tooltip 요소 보이기/숨기기 방법

 

title 속성 생성 방법

※ class 속성의 속성값과 동일한 값을 갖는 title 속성을 JS로 생성.

  • 장점 - 구현 간단
  • 단점 - 로드 느림

 

<meta name="viewport" content="width=device-width, initial-scale=1">


<style>

.box {

  background-color: red;

  height: 5000px;

}


.box img {

  width: calc(100% / 3);

  height: auto;

  float: left;

  margin-bottom:10px;

}


.normal {mix-blend-mode: normal;}

.multiply {mix-blend-mode: multiply;}

.screen {mix-blend-mode: screen;}

.overlay {mix-blend-mode: overlay;}

.darken {mix-blend-mode: darken;}

.lighten {mix-blend-mode: lighten;}

.color-dodge {mix-blend-mode: color-dodge;}

.color-burn {mix-blend-mode: color-burn;}

.hard-light {mix-blend-mode: hard-light;}

.soft-light {mix-blend-mode: soft-light;}    

.difference {mix-blend-mode: difference;}

.exclusion {mix-blend-mode: exclusion;}

.hue {mix-blend-mode: hue;}

.saturation {mix-blend-mode: saturation;}

.color {mix-blend-mode: color;}

.luminosity {mix-blend-mode: luminosity;}

</style>


<div class="box">

  <img src="https://source.unsplash.com/random" alt="이미지" class="normal">

  <img src="https://source.unsplash.com/random" alt="이미지" class="multiply">

  <img src="https://source.unsplash.com/random" alt="이미지" class="screen">

  <img src="https://source.unsplash.com/random" alt="이미지" class="overlay">

  <img src="https://source.unsplash.com/random" alt="이미지" class="darken">

  <img src="https://source.unsplash.com/random" alt="이미지" class="lighten">

  <img src="https://source.unsplash.com/random" alt="이미지" class="color-dodge">

  <img src="https://source.unsplash.com/random" alt="이미지" class="color-burn">

  <img src="https://source.unsplash.com/random" alt="이미지" class="hard-light">

  <img src="https://source.unsplash.com/random" alt="이미지" class="soft-light">   <img src="https://source.unsplash.com/random" alt="이미지" class="difference">

  <img src="https://source.unsplash.com/random" alt="이미지" class="exclusion">

  <img src="https://source.unsplash.com/random" alt="이미지" class="hue">

  <img src="https://source.unsplash.com/random" alt="이미지" class="saturation">

  <img src="https://source.unsplash.com/random" alt="이미지" class="color">

  <img src="https://source.unsplash.com/random" alt="이미지" class="luminosity">

</div>


<script>

document.addEventListener('DOMContentLoaded', function() {

  var images = document.querySelectorAll('.box img');


  images.forEach(function(image) {

    var className = image.getAttribute('class');

    image.setAttribute('title', className);

  });

});

</script>

 

결과보기

 

tooltip 요소 생성 방법

※ JS로 툴팁요소 생성해 띄움.

  • 장점: 로드 빠름.
  • 단점: 코드 복잡 

 

<meta name="viewport" content="width=device-width, initial-scale=1">


<style>

  .box {

    background-color: red;

    height: 5000px;

    position: relative;

  }


  .box img {

    width: calc(100% / 3);

    height: auto;

    float: left;

    margin-bottom: 10px;

    position: relative;

  }


.normal {mix-blend-mode: normal;}

.multiply {mix-blend-mode: multiply;}

.screen {mix-blend-mode: screen;}

.overlay {mix-blend-mode: overlay;}

.darken {mix-blend-mode: darken;}

.lighten {mix-blend-mode: lighten;}

.color-dodge {mix-blend-mode: color-dodge;}

.color-burn {mix-blend-mode: color-burn;}

.hard-light {mix-blend-mode: hard-light;}

.soft-light {mix-blend-mode: soft-light;}    

.difference {mix-blend-mode: difference;}

.exclusion {mix-blend-mode: exclusion;}

.hue {mix-blend-mode: hue;}

.saturation {mix-blend-mode: saturation;}

.color {mix-blend-mode: color;}

.luminosity {mix-blend-mode: luminosity;}    

    

.tooltip {

    display: none;

    position: absolute;

    background-color: #fff;

    padding: 10px;

    border: 1px solid #000;

    top: 0;

    left: 100%;

}

</style>


<div class="box">

  <img src="https://source.unsplash.com/random" alt="이미지" class="normal">

  <img src="https://source.unsplash.com/random" alt="이미지" class="multiply">

  <img src="https://source.unsplash.com/random" alt="이미지" class="screen">

  <img src="https://source.unsplash.com/random" alt="이미지" class="overlay">

  <img src="https://source.unsplash.com/random" alt="이미지" class="darken">

  <img src="https://source.unsplash.com/random" alt="이미지" class="lighten">

  <img src="https://source.unsplash.com/random" alt="이미지" class="color-dodge">

  <img src="https://source.unsplash.com/random" alt="이미지" class="color-burn">

  <img src="https://source.unsplash.com/random" alt="이미지" class="hard-light">

  <img src="https://source.unsplash.com/random" alt="이미지" class="soft-light">   <img src="https://source.unsplash.com/random" alt="이미지" class="difference">

  <img src="https://source.unsplash.com/random" alt="이미지" class="exclusion">

  <img src="https://source.unsplash.com/random" alt="이미지" class="hue">

  <img src="https://source.unsplash.com/random" alt="이미지" class="saturation">

  <img src="https://source.unsplash.com/random" alt="이미지" class="color">

  <img src="https://source.unsplash.com/random" alt="이미지" class="luminosity">

</div>


<script>

document.addEventListener('DOMContentLoaded', function() {

    var images = document.querySelectorAll('.box img');


    images.forEach(function(image) {

      var className = image.getAttribute('class');

      var tooltip = document.createElement('span');

      tooltip.classList.add('tooltip');

      tooltip.textContent = className;

      image.parentElement.appendChild(tooltip);


      image.addEventListener('mouseover', function() {

        tooltip.style.display = 'block';

      });


      image.addEventListener('mouseout', function() {

        tooltip.style.display = 'none';

      });


      // 이미지 감싸는 .box 요소의 상대위치 기준으로 툴팁 위치 설정

      image.addEventListener('mousemove', function(event) {

        var x = event.clientX;

        var y = event.clientY + window.scrollY; // 스크롤 위치를 고려합니다.

        tooltip.style.top = y + 'px';

        tooltip.style.left = x + 'px';

      });

    });


    // 스크롤 이벤트 사용해 툴팁 위치 조정

    window.addEventListener('scroll', function() {

      var tooltips = document.querySelectorAll('.tooltip');

      tooltips.forEach(function(tooltip) {

        var y = parseFloat(tooltip.style.top);

        y += window.scrollY;

        tooltip.style.top = y + 'px';

      });

    });

});

</script>

 

결과보기

 

tooltip 요소 보이기/숨기기 방법

 ※ 툴팁요소를 미리 만들어 숨긴 후, 허버 시 노출.
장점: 로드 빠름.
단점: 코드 약간 복잡.

 

<meta name="viewport" content="width=device-width, initial-scale=1">


<style>

  .box {

    background-color: red;

    height: 5000px;

    position: relative;

  }


  .box img {

    width: calc(100% / 3);

    height: auto;

    float: left;

    margin-bottom: 10px;

  }


.normal {mix-blend-mode: normal;}

.multiply {mix-blend-mode: multiply;}

.screen {mix-blend-mode: screen;}

.overlay {mix-blend-mode: overlay;}

.darken {mix-blend-mode: darken;}

.lighten {mix-blend-mode: lighten;}

.color-dodge {mix-blend-mode: color-dodge;}

.color-burn {mix-blend-mode: color-burn;}

.hard-light {mix-blend-mode: hard-light;}

.soft-light {mix-blend-mode: soft-light;}    

.difference {mix-blend-mode: difference;}

.exclusion {mix-blend-mode: exclusion;}

.hue {mix-blend-mode: hue;}

.saturation {mix-blend-mode: saturation;}

.color {mix-blend-mode: color;}

.luminosity {mix-blend-mode: luminosity;}


#tooltip {

    display:none;

    position:absolute;

    top:0px;

    left:0px;

    padding:10px;

    background-color:#eeeeee;

    border:1px solid #cccccc"        

}

</style>


<div class="box" id="box">

  <img src="https://source.unsplash.com/random" alt="이미지" class="normal">

  <img src="https://source.unsplash.com/random" alt="이미지" class="multiply">

  <img src="https://source.unsplash.com/random" alt="이미지" class="screen">

  <img src="https://source.unsplash.com/random" alt="이미지" class="overlay">

  <img src="https://source.unsplash.com/random" alt="이미지" class="darken">

  <img src="https://source.unsplash.com/random" alt="이미지" class="lighten">

  <img src="https://source.unsplash.com/random" alt="이미지" class="color-dodge">

  <img src="https://source.unsplash.com/random" alt="이미지" class="color-burn">

  <img src="https://source.unsplash.com/random" alt="이미지" class="hard-light">

  <img src="https://source.unsplash.com/random" alt="이미지" class="soft-light">   <img src="https://source.unsplash.com/random" alt="이미지" class="difference">

  <img src="https://source.unsplash.com/random" alt="이미지" class="exclusion">

  <img src="https://source.unsplash.com/random" alt="이미지" class="hue">

  <img src="https://source.unsplash.com/random" alt="이미지" class="saturation">

  <img src="https://source.unsplash.com/random" alt="이미지" class="color">

  <img src="https://source.unsplash.com/random" alt="이미지" class="luminosity">

  <span id="tooltip"></span>

</div>


<script>

// 여러 이벤트에 동일 실행코드 적용

box.onmouseover = box.onmouseout = function() {

    tooltip.style.display = tooltip.style.display == "block" ? "none" : "block";

}

box.onmousemove = function(e) {

    tooltip.style.top =(e.clientY +  window.scrollY) + "px";

    tooltip.style.left = e.clientX + "px";

}

for (i of box.querySelectorAll("img")) {

     i.onmouseover = function() {

        tooltip.innerHTML = this.className;

    }

}

</script>

 

결과보기 


PS. 마지막 for 반복문 부분을  Array.forEach() 이용해 표현 가능. 이 메서드 적용하려면, 일단 노드를 배열로 변환 필요.

// 방법1 - Array.from() 메서드 이용해 배열로 변환

const imgs = Array.from(box.querySelectorAll("img"));


imgs.forEach(img => {

    img.onmouseover = () => {

        tooltip.innerHTML = img.className;

    };

});


// 방법2 - 전개연산자([... ]) 이용해 배열로 변환

const imgs = [...box.querySelectorAll("img")];


imgs.forEach(img => {

    img.onmouseover = () => {

        tooltip.innerHTML = img.className;

    };

});

 

비타주리 님 (231028) https://sir.kr/qa/515531

방문 감사합니다. (즐겨찾기 등록: Ctrl + D)

분류 제목
js JS - 숫자를 한글로 읽기/변환
js JS - 숫자 천자리 표시 기호 쉼표(콤마) 제거 함수 (= getInt함수 = 겟인트함수)
js JS - 랜덤이미지 (= 랜덤배너)
js JS - 텍스트 첫글자만 글자색 변경 (= 맨앞글자 색상 변경)
js JS - 자바스크립트 성능 향상 위한 코드 작성법 (= JavaScript Performance)
DOM_Style JS - aspectRatio 속성 - 요소의 종횡비율(= 가로세로비율) 지정 (= aspectRatio속성…
js JS - with 키워드 - 객체 이용해 구문작성 (= with키워드 = 위드키워드)
js JS - 입력한 패스워드 확인 (보이기/숨기기) 토글 버튼 넣기
js JS - JavaScript로 (SlideUp/SlideDown) (FadeOut/FadeIn) 토글 버튼 …
DOM_Element JS - outerHTML 속성 - 속성, 시작태그, 종료태그 포함한 HTML 요소 설정/반환 (= oute…
Array JS - includes() 메서드 - 배열에 지정값 포함 여부 검사체크 (= includes메서드 = 인클…
js JS - 이미지 위에 마우스허버 시 툴팁창(Tooltip) 띄우기 ※ 클래스 속성값과 동일한 타이틀 속성 생…
Array JS - at() 메서드 - 지정 색인번호의 배열값 반환 (= at메서드 = 엣메서드/앳메서드)
Array JS - entries() 예제 - 객체배열반복자 반환 (= entries메서드 = 엔트리즈메서드)
Array JS - flat() 예제 - 배열 평탄화 (= flat메서드 = 플랫메서드) ※ 중첩배열(=다단계배열)의 …
Array JS - flatMap() 메서드 - 배열 매핑 후 지정함수 적용한 새 평면배열 생성 (= flatMap메서…
Array JS - Array.from() 메서드 - 객체로부터 배열 생성 (= Array.from메서드 = 어레이프럼…
Array JS - keys() 메서드 - 배열키로 구성된 배열 반환 (= keys메서드 = 키즈메서드)
Math JS - Math.log2() 메서드 -
Math JS - Math.log10() 메서드 -
66/67
목록
찾아주셔서 감사합니다. Since 2012