<header>
  <h2 class="title">MouseEvent.relatedTarget</h2>
  <p class="description">Визначаємо елемент, на який перейшов курсор після виходу з іншого елемента</p>
</header>
<main>
  <div class="result">
    <!-- Блок з інтерактивними елементами -->
    <button class="hover-button" id="myButton">Наведи на мене</button>
    <div class="target-zone" id="targetZone">Перемістіть курсор сюди</div>
    <p id="log"></p> <!-- Для виведення результату -->
  </div>
</main>
body {
  font-size: 16px;
  line-height: 1.5;
  font-family: monospace;
}

header {
  background-color: #f1f1f1;
  margin-bottom: 25px;
  padding: 15px;
  box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
}

header h2.title {
  padding-bottom: 15px;
  border-bottom: 1px solid #999;
}

header p.description {
  font-style: italic;
  color: #222;
}

.result {
  background-color: #f8f8f8;
  padding: 15px;
  box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
}

.hover-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

.hover-button:hover {
  background-color: #0056b3;
}

.target-zone {
  width: 200px;
  height: 100px;
  background-color: #e9ecef;
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #333;
  border: 1px solid #ccc;
}
const button = document.getElementById("myButton");
const targetZone = document.getElementById("targetZone");
const log = document.getElementById("log");

button.addEventListener("mouseleave", (event) => {
  if (event.relatedTarget === targetZone) {
    button.style.backgroundColor = "#28a745"; // Зелений, якщо курсор націлений на зону
    log.innerText = "Курсор перейшов на зону!";
  } else {
    button.style.backgroundColor = "#dc3545"; // Червоний для інших елементів
    log.innerText = "Курсор залишив кнопку.";
  }
});

button.addEventListener("mouseenter", () => {
  button.style.backgroundColor = "#007bff"; // Відновлення кольору при наведенні
  log.innerText = ""; // Очищення логу
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.