Всем привет! Есть кнопки, по нажатию на которые появляется различный контент, по механике табов. В футере на небольшое оглавление я повесила якорные ссылки к этим табам, но, логично, что при переходе к якорю кнопка не получает фокус. Нужно чтоб получала, то есть при переходе по якорю раскрывался нужный контент. Это можно как-то сделать? Сss/js не принципиально, заранее спасибо!
1 ответ
Можно, с помощью JavaScript/jQuery
- Добавить уникальный
id
для каждой кнопки, который будет открывать нужный контент. - В якорные ссылке добавить
href
с уникальным id кнопки к которой она относится. - Через JavaScript либо jQuery искать все якорные ссылки на странице, и для каждой ссылки добавлять обработчик события клика, который при переходе по ссылке будет находить нужную кнопку и нажимать её
Реализация через JavaScript:
// Get all anchor links on the page
const anchors = document.querySelectorAll('a[href^="#"]');
// Add event listener for each anchor link
anchors.forEach(function (anchor) {
anchor.addEventListener('click', function (e) {
e.preventDefault(); // Prevent default behavior of the link
// Get the id of the button to which the anchor link is related
const targetId = this.getAttribute('href');
// Find the target button by its id
const targetButton = document.querySelector(targetId);
// If the button is found, click it
if (targetButton) {
targetButton.click();
}
});
});
Реализация через jQuery:
// Add event listener for each anchor link
$('a[href^="#"]').click(function(e) {
e.preventDefault(); // Prevent default behavior of the link
// Get the id of the button to which the anchor link is related
const targetId = $(this).attr('href');
// Find the target button by its id
const targetButton = $(targetId);
// If the button is found, click it
if (targetButton.length) {
targetButton.click();
}
});