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

[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)

분류 제목
Basic JS - Home (JS입문) + Javascript Framework (프레임워크) 종류
Basic JS - Intro (JS소개)
Basic JS - Where To (JS위치) - JS구문 / JS코드위치 / JS사용법 ※ JS외부링크 주의사항
Basic JS - Output (JS출력= JS쓰기) ★★★★★
Basic JS - Syntax (JS구문) ★
Basic JS - Statement (JS구문= JS명령문)
Basic JS - Comment (JS주석)
Basic JS - Variable (JS변수) ★★★★★
Basic JS - Operator (연산자) - JS연산자 ★★★★★
Basic JS - Data Type - 데이터유형 ★★★★★ (= 데이터형식 = 데이터타입 = 데이터종류 = 자료형…
Basic JS - Function - JS함수 ★★★★★ ※ 일반함수 특징 2
Basic JS - Object - JS객체 ★★★★★
Basic JS - Scope - JS유효범위 (= JS접근범위 = 변수 종류) ★★★★★★★★★★
Basic JS - Event - JS이벤트 (= JS코드실행방법) ★★★★★
Basic JS - Strings - JS문자열
Basic JS - String Methods - JS문자열메서드
Basic JS - Number - JS숫자
Basic JS - Number Method - JS숫자메서드
Basic JS - Math 객체 - JS수학객체 (= JS산수객체 = Math객체 = Math Object = 매스 …
Basic JS - Dates - JS날짜
1/67
목록
찾아주셔서 감사합니다. Since 2012