SeouliteLab

jQuery 이벤트 객체의 relatedTarget 속성 활용하기 본문

프로그래밍

jQuery 이벤트 객체의 relatedTarget 속성 활용하기

Seoulite Lab 2024. 4. 2. 13:34

웹 페이지에서 마우스 이벤트가 발생할 때, 이벤트가 일어난 요소와 관련된 요소를 식별하는 데에 사용되는 속성 중 하나가 relatedTarget입니다. jQuery의 event.relatedTarget 속성은 이벤트와 관련된 다른 요소를 제공하여 상호작용을 더욱 효과적으로 처리할 수 있습니다.

예제 1: 마우스 이벤트에서 관련 요소 확인하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery 이벤트 객체의 relatedTarget 속성 활용하기</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('div').mouseenter(function(event){
        $('#result1').text('마우스가 진입한 요소: ' + this.id);
        $('#result2').text('마우스가 이전에 있던 요소: ' + event.relatedTarget.id);
      });
    });
  </script>
</head>
<body>

<div id="box1" style="width: 100px; height: 100px; background-color: lightblue;"></div>
<div id="box2" style="width: 100px; height: 100px; background-color: lightgreen;"></div>

<p id="result1"></p>
<p id="result2"></p>

</body>
</html>

결과:

  • 박스1에 마우스를 진입하면 해당 요소와 관련된 요소로 자기 자신이, 이전에 마우스가 있던 요소로는 null이 출력됩니다.
  • 박스2에 마우스를 진입하면 해당 요소와 관련된 요소로 자기 자신이, 이전에 마우스가 있던 요소로는 박스1의 id가 출력됩니다.

설명:
이 예제에서는 마우스 이벤트가 발생했을 때 해당 요소와 관련된 다른 요소를 확인하는 방법을 보여줍니다. mouseenter 이벤트가 발생할 때 현재 요소와 이전에 마우스가 있던 요소를 relatedTarget 속성을 통해 확인합니다.


예제 2: 마우스 이벤트에서 관련 요소에 따른 동작 처리하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery 이벤트 객체의 relatedTarget 속성 활용하기</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('div').mouseleave(function(event){
        if (event.relatedTarget && event.relatedTarget.id === 'box1') {
          $(this).text('박스1에서 나갔습니다.');
        } else if (event.relatedTarget && event.relatedTarget.id === 'box2') {
          $(this).text('박스2에서 나갔습니다.');
        } else {
          $(this).text('다른 곳에서 나갔습니다.');
        }
      });
    });
  </script>
</head>
<body>

<div id="box1" style="width: 100px; height: 100px; background-color: lightblue;"></div>
<div id="box2" style="width: 100px; height: 100px; background-color: lightgreen;"></div>

<p>마우스를 박스 안에서 이동해보세요.</p>
<p id="result"></p>

</body>
</html>

결과:

  • 박스1에서 박스 외부로 나가면 해당 박스에 '박스1에서 나갔습니다.'가 출력됩니다.
  • 박스2에서 박스 외부로 나가면 해당 박스에 '박스2에서 나갔습니다.'가 출력됩니다.
  • 다른 곳에서 박스 외부로 나가면 해당 박스에 '다른 곳에서 나갔습니다.'가 출력됩니다.

설명:
이 예제에서는 마우스 이벤트가 발생했을 때 관련 요소에 따라 다른 동작을 처리하는 방법을 보여줍니다. mouseleave 이벤트가 발생했을 때 이전 요소가 박스1인 경우에는 해당 박스에 '박스1에서 나갔습니다.'를 출력하고, 박스2인 경우에는

'박스2에서 나갔습니다.'를 출력합니다. relatedTarget을 활용하여 이전에 마우스가 있던 요소를 확인하고, 그에 따라 동작을 조절합니다.


예제 3: 키보드 이벤트에서 관련 요소 확인하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery 이벤트 객체의 relatedTarget 속성 활용하기</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('input').focus(function(event){
        $('#result').text('이전 포커스 요소: ' + event.relatedTarget);
      });
    });
  </script>
</head>
<body>

<input type="text" placeholder="이곳을 클릭해보세요">

<p id="result"></p>

</body>
</html>

결과:

  • 입력 필드를 클릭하면 이전 포커스 요소로 null이 출력됩니다.

설명:
이 예제에서는 입력 필드를 클릭했을 때 이전 포커스 요소를 확인하는 방법을 보여줍니다. focus 이벤트가 발생했을 때 이전에 포커스가 있던 요소를 relatedTarget 속성을 통해 확인합니다.


예제 4: 이벤트 버블링을 이용한 관련 요소 확인하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery 이벤트 객체의 relatedTarget 속성 활용하기</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('ul').click(function(event){
        $('#result').text('클릭한 요소: ' + event.target.tagName + ', 이전 요소: ' + event.relatedTarget.tagName);
      });
      $('li').click(function(event){
        event.stopPropagation();
      });
    });
  </script>
</head>
<body>

<ul>
  <li>항목 1</li>
  <li>항목 2</li>
  <li>항목 3</li>
</ul>

<p id="result"></p>

</body>
</html>

결과:

  • 각 항목을 클릭하면 해당 요소와 관련된 요소로는 null이 출력됩니다.

설명:
이 예제에서는 이벤트 버블링을 이용하여 관련 요소를 확인하는 방법을 보여줍니다. ul 요소에 click 이벤트가 발생했을 때 클릭한 요소와 이전 요소를 확인합니다. 이때 li 요소에 대한 click 이벤트는 event.stopPropagation()을 사용하여 이벤트 버블링을 중지시킵니다.


예제 5: 마우스 이벤트에서 관련 요소의 클래스 확인하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery 이벤트 객체의 relatedTarget 속성 활용하기</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    .highlight {
      background-color: yellow;
    }
  </style>
  <script>
    $(document).ready(function(){
      $('div').mouseenter(function(event){
        if ($(event.relatedTarget).hasClass('highlight')) {
          $(this).addClass('highlight');
        }
      });
      $('div').mouseleave(function(event){
        if ($(event.relatedTarget).hasClass('highlight')) {
          $(this).removeClass('highlight');
        }
      });
    });
  </script>
</head>
<body>

<div class="highlight" style="width: 100px; height: 100px; background-color: lightblue;"></div>
<div class="highlight" style="width: 100px; height: 100px; background-color: lightgreen;"></div>

<p>마우스를 각 박스 사이를 이동해보세요.</p>

</body>
</html>

결과:

  • 마우스가 한 박스에서 다른 박스로 이동하면 해당 박스가 하이라이트되어 배경색이 노란색으로 바뀝니다.

설명:
이 예제에서는 마우스 이벤트가 발생했을 때 관련 요소의 클래스를 확인하여 특정 동작을 처리하는 방법을 보여줍니다. mouseenter 이벤트에서는 relatedTarget의 클래스가 'highlight'인 경우 해당 요소에 'highlight' 클래스를 추가하고, mouseleave 이벤트에서는 relatedTarget의 클래스가 'highlight'인 경우 해당 요소의 'highlight' 클래스를 제거합니다.

jQuery의 event.relatedTarget 속성을 활용하면 이벤트와 관련된 다른 요소를 식별하여 원하는 동작을 처리할 수 있습니다. 이를 통해 웹 애플리케이션에서 상호작용성을 향상시키고 사용자 경험을 향상시킬 수 있습니다.