<header>
  <h2 class="title">Використання події HashChange</h2>
  <p class="description">Цей приклад показує, як використовувати подію HashChange для зміни контенту без перезавантаження сторінки.</p>
</header>
<main>
  <div class="result">
    <div class="navigation">
      <button id="btnSection1">Перейти до Секції 1</button>
      <button id="btnSection2">Перейти до Секції 2</button>
      <button id="btnSection3">Перейти до Секції 3</button>
    </div>
    <div id="content" class="content">
      Виберіть секцію для перегляду.
    </div>
  </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);
}

.navigation {
  margin-bottom: 15px;
}

button {
  padding: 10px 15px;
  margin-right: 10px;
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
}

button:hover {
  background-color: #45a049;
}

.content {
  padding: 20px;
  background-color: #eaeaea;
  border-radius: 5px;
}
// Отримуємо елементи кнопок і контенту
const btnSection1 = document.getElementById('btnSection1');
const btnSection2 = document.getElementById('btnSection2');
const btnSection3 = document.getElementById('btnSection3');
const content = document.getElementById('content');

// Функція для оновлення контенту залежно від хеша
function updateContent() {
  const hash = location.hash.substring(1); // отримуємо хеш з URL

  if (hash === 'section1') {
    content.innerHTML = '<h3>Секція 1</h3><p>Контент першої секції.</p>';
  } else if (hash === 'section2') {
    content.innerHTML = '<h3>Секція 2</h3><p>Контент другої секції.</p>';
  } else if (hash === 'section3') {
    content.innerHTML = '<h3>Секція 3</h3><p>Контент третьої секції.</p>';
  } else {
    content.innerHTML = 'Виберіть секцію для перегляду.';
  }
}

// Додаємо обробники для кнопок
btnSection1.addEventListener('click', function() {
  location.hash = 'section1';  // змінюємо хеш на section1
});

btnSection2.addEventListener('click', function() {
  location.hash = 'section2';  // змінюємо хеш на section2
});

btnSection3.addEventListener('click', function() {
  location.hash = 'section3';  // змінюємо хеш на section3
});

// Додаємо обробник події hashchange
window.addEventListener('hashchange', updateContent);

// Оновлюємо контент при завантаженні сторінки
updateContent();

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.