ある団体のホームページ(Cocoonテーマを使用したWordPressサイト)を運営しています。
このサイトでは、タブを使用して記事タイトルを表示していますが、未選択タブ内の記事はアクセス数が低くなる傾向がありす。
そこで対策として、javascript.js にて、各タブ内に「New!」マーク付きの記事タイトルが存在する場合、該当タブにも「New!」マークを表示するようにしました。
また、ユーザーがそのタブを一度開いた際には、タブ側の「New!」マークを自動で消す仕様にしています。
主な動作は以下の通りです。
- タブ内に .new-txt が存在するか確認
- 存在する場合は、タブラベルに New! を表示
- タブを開いたら New! を削除
javascript
document.addEventListener("DOMContentLoaded", function () {
const maxRetry = 20;
function setNewMark(tabId) {
let retry = 0;
const checkNew = function () {
const tabInput = document.querySelector('#' + tabId);
if (!tabInput) return;
const tabContent = tabInput.nextElementSibling
? tabInput.nextElementSibling.nextElementSibling
: null;
if (!tabContent) return;
const hasNew = tabContent.querySelector('.new-txt') !== null;
const label = document.querySelector('label[for="' + tabId + '"]');
if (!label) return;
// 一度消したら再表示しない
if (label.classList.contains('new-checked')) return;
if (hasNew) {
if (!label.querySelector('.tab-new')) {
let text = label.textContent
.replace(/New!/g, '')
.replace(/\s+/g, ' ')
.trim();
label.innerHTML = 'New! ' + text;
}
}
retry++;
if (retry < maxRetry) {
setTimeout(checkNew, 500);
}
};
checkNew();
}
function addClickRemove(tabId) {
const label = document.querySelector('label[for="' + tabId + '"]');
if (!label) return;
label.addEventListener('click', function () {
const newMark = label.querySelector('.tab-new');
if (newMark) {
newMark.remove();
}
label.classList.add('new-checked');
});
}
setNewMark('TAB-1-2');
setNewMark('TAB-1-3');
addClickRemove('TAB-1-2');
addClickRemove('TAB-1-3');
});



