generated from muhtadeetaron/nextjs-template
initial commit
This commit is contained in:
638
newspaper/assets/js/custom-elements.js
Normal file
638
newspaper/assets/js/custom-elements.js
Normal file
@ -0,0 +1,638 @@
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
if (!customElements.get('custom-header')) {
|
||||
customElements.define('custom-header', class CustomHeader extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.setSocials(this);
|
||||
this.setNavigation(this);
|
||||
this.secondLevelMenu();
|
||||
}
|
||||
|
||||
setSocials(){
|
||||
const data = this.querySelector('#socials-info').dataset.urls;
|
||||
let splitArray = data.toString().toLowerCase().split(',');
|
||||
|
||||
const keyValuePairs = splitArray.map(item => {
|
||||
const match = item.match(/([^:]+):(.*)/);
|
||||
if (match) {
|
||||
const key = match[1].trim();
|
||||
const value = match[2].trim();
|
||||
return { key, value };
|
||||
}
|
||||
return null;
|
||||
}).filter(item => item !== null);
|
||||
|
||||
keyValuePairs.forEach(el => {
|
||||
let element = this.querySelector(`#${el.key.replace(' ', '')}`)
|
||||
if(!element) return;
|
||||
|
||||
element.style.display = "flex";
|
||||
element.href = el.value.replace(' ', '');
|
||||
|
||||
//socials for footer
|
||||
let footerElement = document.querySelector(`#${el.key.replace(' ', '')}-footer`);
|
||||
if(!footerElement) return;
|
||||
|
||||
footerElement.style.display = "flex";
|
||||
footerElement.href = el.value.replace(' ', '');
|
||||
})
|
||||
}
|
||||
|
||||
setNavigation(){
|
||||
const menuBtn = this.querySelector('.menu-button');
|
||||
const menu = this.querySelector('.navbar-links-outer');
|
||||
const navbar = this;
|
||||
menu.style.transition = 'opacity 0.3s var(--ease-transition)';
|
||||
|
||||
menuBtn.addEventListener('click', e => menuHandler(e));
|
||||
window.addEventListener('resize', debounce(() => {menuOnResize()}, 100)); //leave at 100, if smaller there is a bug with scrolling to the top
|
||||
|
||||
function menuHandler(e){
|
||||
if(menu.getAttribute('isopen') == 'true'){
|
||||
closeMenu();
|
||||
}else{
|
||||
openMenu();
|
||||
}
|
||||
}
|
||||
|
||||
function closeMenu(){
|
||||
enableScrolling();
|
||||
|
||||
if(window.matchMedia('(max-width: 991px)').matches){
|
||||
setTimeout(() => {
|
||||
menu.style.display = 'none';
|
||||
menu.setAttribute("isopen", false);
|
||||
}, 300);
|
||||
menu.style.opacity = '0';
|
||||
}
|
||||
|
||||
menuBtn.querySelector('.first-line').style.position = 'static';
|
||||
menuBtn.querySelector('.first-line').style.transform = 'rotateZ(0deg)';
|
||||
menuBtn.querySelector('.second-line').style.position = 'static';
|
||||
menuBtn.querySelector('.second-line').style.transform = 'rotateZ(0deg)';
|
||||
menuBtn.querySelector('.mobile-line').style.opacity = '1';
|
||||
}
|
||||
|
||||
function openMenu(){
|
||||
let currentPosition = window.pageYOffset;
|
||||
let announcementBar = document.querySelector('#announcement-bar-root');
|
||||
let announcementBarOffset = 0;
|
||||
|
||||
if(announcementBar && (currentPosition < announcementBar.offsetHeight)){
|
||||
announcementBarOffset = announcementBar.offsetHeight - currentPosition;
|
||||
}
|
||||
|
||||
disableScrolling();
|
||||
menu.setAttribute("isopen", true);
|
||||
|
||||
menu.style.display = 'flex';
|
||||
setTimeout(() => {
|
||||
menu.style.opacity = '1';
|
||||
}, 10);
|
||||
|
||||
|
||||
menu.style.height = `calc(100dvh - ${navbar.offsetHeight}px - ${announcementBarOffset}px)`;
|
||||
menuBtn.querySelector('.first-line').style.position = 'absolute';
|
||||
menuBtn.querySelector('.first-line').style.transform = 'rotateZ(-45deg)';
|
||||
menuBtn.querySelector('.second-line').style.position = 'absolute';
|
||||
menuBtn.querySelector('.second-line').style.transform = 'rotateZ(45deg)';
|
||||
menuBtn.querySelector('.mobile-line').style.opacity = '0';
|
||||
}
|
||||
|
||||
function menuOnResize(){
|
||||
if(window.matchMedia('(max-width: 991px)').matches){
|
||||
menu.classList.remove('desktop-navbar')
|
||||
}else{
|
||||
menu.classList.add('desktop-navbar');
|
||||
enableScrolling(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
secondLevelMenu(){
|
||||
let navArray = [];
|
||||
const navbar = this.querySelector('.nav');
|
||||
if(navbar){
|
||||
navbar.querySelectorAll('li').forEach(link => {
|
||||
if (link.dataset.label.charAt(0) === "-") {
|
||||
link.dataset.parent = link.dataset.label.substring(1);
|
||||
if(link.dataset.label.includes("--")){
|
||||
var data = link.dataset.parent.split("--")
|
||||
link.dataset.parent = data[0];
|
||||
link.dataset.child = data[1];
|
||||
|
||||
link.querySelector('.nav-link').innerHTML = link.dataset.child;
|
||||
link.querySelector('.nav-link').setAttribute('tabindex', '0');
|
||||
navArray.push({parent: data[0], child: link});
|
||||
}else{
|
||||
link.querySelector('.nav-link').innerHTML = link.dataset.parent;
|
||||
|
||||
const anchor = link.querySelector('a');
|
||||
const div = document.createElement('div');
|
||||
const ul = document.createElement('ul');
|
||||
const container = document.createElement('div')
|
||||
|
||||
div.innerHTML = anchor.innerHTML;
|
||||
div.classList.add('links-label');
|
||||
div.dataset.label = link.dataset.parent;
|
||||
div.innerHTML += `
|
||||
<svg class="dropdown-arrow-svg" viewBox="0 0 9 5" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M4.09103 3.18205L0.908974 0L0 0.908974L4.09103 5L8.18205 0.908974L7.27243 0L4.09038 3.18205H4.09103Z" fill="var(--text-color)"/>
|
||||
</svg>
|
||||
`
|
||||
anchor.parentNode.replaceChild(div, anchor);
|
||||
|
||||
link.appendChild(container);
|
||||
container.classList.add('secondary-links');
|
||||
container.appendChild(ul)
|
||||
ul.classList.add('secondary-links-inner');
|
||||
|
||||
//secondary links handler for mobile
|
||||
div.addEventListener('click', e => this.openCloseLinksOnMobile(link));
|
||||
window.addEventListener('resize', debounce(() => {this.secondaryLinksOnResize(link)}, 10));
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
//move links
|
||||
navArray.forEach(item => {
|
||||
var secondaryList = document.querySelector(`.nav div.links-label[data-label="${item.parent}"]`).parentNode.querySelector('ul');
|
||||
item.child.querySelector('a').classList.remove('hover-underline');
|
||||
secondaryList.appendChild(item.child);
|
||||
})
|
||||
|
||||
navbar.style.display = 'flex';
|
||||
}
|
||||
}
|
||||
|
||||
openCloseLinksOnMobile(link){
|
||||
if(window.matchMedia('(max-width: 991px)').matches){
|
||||
let container = link.querySelector('.secondary-links');
|
||||
if(container.offsetHeight == 0){
|
||||
container.style.height = 'auto';
|
||||
link.querySelector('.dropdown-arrow-svg').style.transform = "rotateZ(180deg) translateX(-100%)";
|
||||
}else{
|
||||
container.style.height = '0px'
|
||||
link.querySelector('.dropdown-arrow-svg').style.transform = "rotateZ(360deg) translateX(100%)";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
secondaryLinksOnResize(link){
|
||||
let container = link.querySelector('.secondary-links');
|
||||
if(window.matchMedia('(max-width: 991px)').matches){
|
||||
container.style.height = '0px'
|
||||
link.querySelector('.dropdown-arrow-svg').style.transform = "rotateZ(0deg) translateX(100%)";
|
||||
}else{
|
||||
container.style.height = 'auto';
|
||||
link.querySelector('.dropdown-arrow-svg').style.transform = "rotateZ(0deg) translateX(0%)";
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
if (!customElements.get('custom-announcement-bar')) {
|
||||
customElements.define('custom-announcement-bar', class CustomAnnouncementBar extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.barType = this.getAttribute('data-announcement-bar-type');
|
||||
this.container = document.querySelector('#announcement-bar-root');
|
||||
this.querySelector('.announcement-close-button').addEventListener('click', () => {
|
||||
if(this.container.querySelector('button')){
|
||||
this.container.querySelector('button').click();
|
||||
this.style.display = "none";
|
||||
}
|
||||
})
|
||||
|
||||
this.setAnnouncementBar();
|
||||
}
|
||||
|
||||
setAnnouncementBar(){
|
||||
if(!this.container || this.barType == "Normal") {
|
||||
this.hideCustomAnnouncementBar();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if children are already present
|
||||
if (this.container.children.length > 0) {
|
||||
this.setAnnouncementBarData(this.container.querySelector('.gh-announcement-bar-content'));
|
||||
this.showCustomAnnouncementBar();
|
||||
}
|
||||
|
||||
const handleChildChange = (mutationsList, observer) => {
|
||||
for (const mutation of mutationsList) {
|
||||
if (mutation.type === "childList") {
|
||||
// Child elements have been added or removed
|
||||
const numChildren = this.container.children.length;
|
||||
if(numChildren > 0){
|
||||
this.setAnnouncementBarData(this.container.querySelector('.gh-announcement-bar-content'));
|
||||
this.showCustomAnnouncementBar();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const observer = new MutationObserver(handleChildChange);
|
||||
const config = { childList: true };
|
||||
observer.observe(this.container, config);
|
||||
}
|
||||
|
||||
showCustomAnnouncementBar(){
|
||||
this.container.style.display = "none";
|
||||
this.style.display = "flex";
|
||||
}
|
||||
|
||||
hideCustomAnnouncementBar(){
|
||||
if(this.container){
|
||||
this.container.style.display = "block";
|
||||
}
|
||||
this.style.display = "none";
|
||||
}
|
||||
|
||||
setAnnouncementBarData(text){
|
||||
switch (this.barType) {
|
||||
case "Moving Several News":
|
||||
let sentences = text.textContent.split('.');
|
||||
let filteredSentences = sentences.filter(sentence => sentence.trim() !== '');
|
||||
|
||||
this.querySelectorAll('.announcement-text').forEach(item => {
|
||||
item.innerHTML = "";
|
||||
filteredSentences.forEach(sentence => {
|
||||
item.classList.add('slide-animation');
|
||||
item.innerHTML += sentence;
|
||||
item.innerHTML += `
|
||||
<div class="announcement-circle"></div>
|
||||
`
|
||||
})
|
||||
})
|
||||
break;
|
||||
|
||||
case "Moving One News":
|
||||
this.querySelectorAll('.announcement-text').forEach(item => {
|
||||
item.classList.add('slide-animation');
|
||||
item.innerHTML = text.innerHTML;
|
||||
})
|
||||
break;
|
||||
|
||||
case "Static":
|
||||
this.querySelectorAll('.announcement-text').forEach(item => {
|
||||
item.innerHTML = text.innerHTML;
|
||||
item.classList.remove('slide-animation')
|
||||
})
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (!customElements.get('custom-pagination')) {
|
||||
customElements.define('custom-pagination', class CustomPagination extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.loadMoreBtn = this.querySelector("#load-more-btn");
|
||||
|
||||
if(this.loadMoreBtn){
|
||||
this.loadMoreBtn.addEventListener("click", () => {
|
||||
this.loadMorePosts();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
loadMorePosts(cleanList = false) {
|
||||
let currentPage = parseInt(this.getAttribute("data-current-page"));
|
||||
let nextPage = cleanList ? currentPage = 1 : currentPage + 1;
|
||||
let startUrl = window.location;
|
||||
|
||||
if(this.getAttribute('data-is-archivepage') == "true"){
|
||||
let tagName = document.querySelector('archive-tags').getAttribute('data-current-tag')
|
||||
tagName == "all-tags" ? startUrl = window.location.origin + "/": startUrl = window.location.origin + `/tag/${tagName}/`
|
||||
}
|
||||
|
||||
let url = startUrl + `page/${nextPage}/`;
|
||||
|
||||
|
||||
// Make the AJAX request
|
||||
fetch(url)
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
let parser = new DOMParser();
|
||||
let html = parser.parseFromString(data, "text/html");
|
||||
let grid = document.querySelector("#pagination-grid");
|
||||
let newPosts = html.querySelector("#pagination-grid").innerHTML;
|
||||
|
||||
// Append the new posts to the existing ones
|
||||
cleanList ? grid.innerHTML = newPosts : grid.insertAdjacentHTML("beforeend", newPosts);
|
||||
|
||||
if(cleanList){
|
||||
let postNumber = html.querySelector('#data-length');
|
||||
if(postNumber){
|
||||
document.querySelector(".archive-grid-article-number").innerHTML = postNumber.getAttribute('data-length');
|
||||
}
|
||||
}
|
||||
|
||||
// Update the "Load more" button attributes
|
||||
this.setAttribute("data-current-page", nextPage);
|
||||
if(this.loadMoreBtn){
|
||||
this.loadMoreBtn.style.display = html.querySelector("#load-more-btn") ? "block" : "none";
|
||||
}
|
||||
|
||||
lazyLoadImages(grid);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error("Error loading more posts:", error);
|
||||
});
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (!customElements.get('archive-tags')) {
|
||||
customElements.define('archive-tags', class ArchiveTags extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.querySelectorAll('.archive-tag-button').forEach(button => {
|
||||
button.addEventListener('change', this.archiveButtonChange.bind(this))
|
||||
})
|
||||
}
|
||||
|
||||
archiveButtonChange(e){
|
||||
this.setAttribute('data-current-tag', e.target.id);
|
||||
|
||||
// Make the AJAX request
|
||||
document.getElementById('custom-pagination').loadMorePosts(true);
|
||||
|
||||
document.querySelector('.archive-grid-title').textContent = e.target.getAttribute('data-name');
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (!customElements.get('featured-tags')) {
|
||||
customElements.define('featured-tags', class FeaturedTags extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
this.tagSlugs = this.getAttribute('data-featured-tags');
|
||||
this.setFeaturedTags();
|
||||
}
|
||||
|
||||
async setFeaturedTags() {
|
||||
const tags = this.tagSlugs.split(',').map(item => item.trim());
|
||||
const grid = this.querySelector('.featured-tags-inner');
|
||||
|
||||
for (const tag of tags) {
|
||||
try {
|
||||
const url = `${window.location.origin}/tag/${tag}/page/1/`;
|
||||
const response = await fetch(url);
|
||||
const data = await response.text();
|
||||
const parser = new DOMParser();
|
||||
const html = parser.parseFromString(data, "text/html");
|
||||
const newPosts = html.querySelector(".articles-grid-section");
|
||||
const newHeading = html.querySelector('.text-card-heading');
|
||||
const articleNumber = html.querySelector('.section-heading-article-number');
|
||||
const button = html.querySelector('#homepage-section-heading-button');
|
||||
|
||||
newPosts.setAttribute('featured-tag-slug', tag);
|
||||
|
||||
// Creating a heading wrapper
|
||||
const headingWrapper = document.createElement('div');
|
||||
headingWrapper.classList.add('sponsored-heading');
|
||||
|
||||
// Clean up new posts
|
||||
newPosts.querySelector('custom-pagination')?.remove();
|
||||
newPosts.querySelector('.articles-grid-section .section-heading-title').textContent = newHeading.textContent;
|
||||
newPosts.querySelector('.section-heading').insertBefore(headingWrapper, newPosts.querySelector('.section-heading').firstChild);
|
||||
headingWrapper.appendChild(newPosts.querySelector('.articles-grid-section .section-heading-title'));
|
||||
articleNumber.remove();
|
||||
button.classList.remove('hidden');
|
||||
newPosts.querySelector('.pagination-grid').removeAttribute('id');
|
||||
newPosts.querySelector('.section-heading-button')?.removeAttribute('id');
|
||||
|
||||
newPosts.querySelectorAll('.grid-small-card').forEach((card, index) => {
|
||||
if (index > 3) {
|
||||
card.remove();
|
||||
}
|
||||
});
|
||||
|
||||
lazyLoadImages(newPosts);
|
||||
grid.appendChild(newPosts);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error loading more posts:", error);
|
||||
}
|
||||
}
|
||||
|
||||
document.querySelector('.featured-tags-section').style.display = 'block';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (!customElements.get('custom-notifications')) {
|
||||
customElements.define('custom-notifications', class CustomNotifications extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.setNotification();
|
||||
}
|
||||
|
||||
setNotification() {
|
||||
var action = getParameterByName('action');
|
||||
var stripe = getParameterByName('stripe');
|
||||
var success = getParameterByName('success');
|
||||
|
||||
if(success == null && action == null && stripe == null) return;
|
||||
|
||||
var notifications = document.querySelector('.global-notifications');
|
||||
if(stripe){
|
||||
notifications.classList.add(`stripe-${stripe}`);
|
||||
|
||||
notifications.addEventListener('animationend', () => {
|
||||
notifications.classList.remove(`stripe-${stripe}`);
|
||||
});
|
||||
}else{
|
||||
notifications.classList.add(`${action}-${success}`);
|
||||
|
||||
notifications.addEventListener('animationend', () => {
|
||||
notifications.classList.remove(`${action}-${success}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (!customElements.get('custom-form')) {
|
||||
customElements.define('custom-form', class CustomForm extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
const formElement = this.querySelector('form');
|
||||
const heading = document.querySelector('.form-page-content h1');
|
||||
const description = document.querySelector('.form-page-excerpt');
|
||||
const homeButton = document.querySelector('.form-success-button');
|
||||
const successHeading = this.querySelector("#form-success-heading-text").getAttribute('data-success-heading');
|
||||
const successParagraph = this.querySelector("#form-success-paragraph-text").getAttribute('data-success-paragraph');
|
||||
|
||||
let success = false;
|
||||
const observer = new MutationObserver(function(mutationsList) {
|
||||
for (const mutation of mutationsList) {
|
||||
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
|
||||
const classList = mutation.target.classList;
|
||||
if (classList.contains('success') && !success) {
|
||||
success = true;
|
||||
|
||||
formElement.style.display = "none";
|
||||
|
||||
heading.innerHTML = successHeading;
|
||||
homeButton.style.display = "block";
|
||||
|
||||
description.innerHTML = successParagraph;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
observer.observe(formElement, { attributes: true });
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (!customElements.get('custom-membership')) {
|
||||
customElements.define('custom-membership', class CustomMembership extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
let currencies = [];
|
||||
|
||||
this.querySelectorAll('.membership-button').forEach(button => {
|
||||
button.addEventListener('click', this.tabChange.bind(this))
|
||||
})
|
||||
|
||||
if(!this.querySelector('.tier-card')){
|
||||
this.remove();
|
||||
}
|
||||
|
||||
this.querySelectorAll('.tier-price').forEach(price => {
|
||||
let newText = this.extractCurrency(price.querySelector('.tier-price-span').textContent.toString().trim());
|
||||
|
||||
price.querySelector('.tier-currency').textContent = newText?.currency;
|
||||
price.querySelector('.tier-price-span').textContent = newText?.stringWithoutCurrency;
|
||||
currencies.push(newText?.currency);
|
||||
})
|
||||
|
||||
const currenciesNoEmptyStrings = currencies.filter((str) => str.trim() !== '');
|
||||
|
||||
const cleanedCurrencies = [...new Set(currenciesNoEmptyStrings)];
|
||||
|
||||
this.querySelectorAll('.tier-currency-free').forEach(currency => {
|
||||
|
||||
cleanedCurrencies.length === 0 ? currency.textContent = "$" : currency.textContent = cleanedCurrencies[0];
|
||||
})
|
||||
|
||||
this.style.display = 'block';
|
||||
}
|
||||
|
||||
tabChange(e) {
|
||||
if(e.target.getAttribute('data-inactive') == "true"){
|
||||
e.target.setAttribute('data-inactive', "false");
|
||||
let name = e.target.getAttribute('data-tab')
|
||||
this.querySelector(`.membership-tiers[data-tab-content=${name}]`).setAttribute('data-inactive', "false")
|
||||
|
||||
let oposite;
|
||||
name == "yearly" ? oposite = "monthly" : oposite = "yearly"
|
||||
|
||||
this.querySelector(`.membership-button[data-tab=${oposite}]`).setAttribute('data-inactive', "true");
|
||||
this.querySelector(`.membership-tiers[data-tab-content=${oposite}]`).setAttribute('data-inactive', "true")
|
||||
}
|
||||
}
|
||||
|
||||
extractCurrency(inputString) {
|
||||
const regex = /^(.*?)(?=\d)/;
|
||||
const match = inputString.match(regex);
|
||||
|
||||
if (match) {
|
||||
const currency = match[1];
|
||||
const stringWithoutCurrency = inputString.replace(currency, '');
|
||||
|
||||
return { currency, stringWithoutCurrency };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (!customElements.get('custom-footer')) {
|
||||
customElements.define('custom-footer', class CustomFooter extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.secondLevelFooter(this);
|
||||
}
|
||||
|
||||
secondLevelFooter(){
|
||||
let navArray = [];
|
||||
const footerNav = document.querySelector('.footer-nav');
|
||||
if(footerNav){
|
||||
footerNav.querySelectorAll('li').forEach(link => {
|
||||
if (link.dataset.label.charAt(0) === "-") {
|
||||
|
||||
link.dataset.parent = link.dataset.label.substring(1);
|
||||
if(link.dataset.label.includes("--")){
|
||||
var data = link.dataset.parent.split("--")
|
||||
link.dataset.parent = data[0];
|
||||
link.dataset.child = data[1];
|
||||
|
||||
link.querySelector('.footer-nav-link').innerHTML = link.dataset.child;
|
||||
navArray.push({parent: data[0], child: link});
|
||||
}
|
||||
else{
|
||||
link.querySelector('.footer-nav-link').innerHTML = link.dataset.parent;
|
||||
|
||||
const anchor = link.querySelector('a');
|
||||
const div = document.createElement('div');
|
||||
const ul = document.createElement('ul');
|
||||
const groupUl = document.createElement('ul')
|
||||
|
||||
|
||||
div.innerHTML = anchor.innerHTML;
|
||||
div.classList.add('footer-links-label')
|
||||
groupUl.classList.add('footer-links-group')
|
||||
div.dataset.label = link.dataset.parent;
|
||||
anchor.parentNode.replaceChild(div, anchor);
|
||||
|
||||
link.appendChild(ul);
|
||||
ul.classList.add('footer-secondary-links');
|
||||
|
||||
|
||||
document.querySelector('.footer-navigation').appendChild(groupUl)
|
||||
groupUl.appendChild(link)
|
||||
}
|
||||
}else {
|
||||
document.querySelector('.footer-normal-links').appendChild(link)
|
||||
}
|
||||
})
|
||||
|
||||
//move links
|
||||
navArray.forEach(item => {
|
||||
var secondaryList = this.querySelector(`div.footer-links-label[data-label="${item.parent}"]`).parentNode.querySelector('ul');
|
||||
secondaryList.appendChild(item.child)
|
||||
})
|
||||
|
||||
if(footerNav.children.length === 0){
|
||||
footerNav.remove();
|
||||
}
|
||||
|
||||
if(document.querySelector('.footer-normal-links').children.length === 0){
|
||||
document.querySelector('.footer-normal-links-group').remove();
|
||||
}
|
||||
|
||||
this.querySelector('.footer-navigation').style.display = 'flex';
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
187
newspaper/assets/js/global.js
Normal file
187
newspaper/assets/js/global.js
Normal file
@ -0,0 +1,187 @@
|
||||
function loadFonts(fonts, doc = document){
|
||||
const data = fonts;
|
||||
if(!data) return;
|
||||
const root = document.documentElement;
|
||||
|
||||
let splitArray = data.toString().replace(/,\s*/g, ',').split(',');
|
||||
|
||||
let googleFontsURL = `https://fonts.googleapis.com/css2?`;
|
||||
|
||||
const ghostFonts = document.querySelector('link[href*="fonts.bunny.net/css"]');
|
||||
|
||||
if(ghostFonts) return;
|
||||
|
||||
for(let i = 0; i < splitArray.length; i++){
|
||||
if(i == 4) break;
|
||||
|
||||
root.style.setProperty(`--font${i+1}`, `'${splitArray[i].toString()}'`);
|
||||
|
||||
splitArray[i] = splitArray[i].replace(' ', '+');
|
||||
googleFontsURL += `family=${splitArray[i]}:wght@300;400;500;600;700&`
|
||||
}
|
||||
|
||||
googleFontsURL += 'display=swap'
|
||||
|
||||
const linkElement = doc.createElement('link');
|
||||
linkElement.rel = 'stylesheet';
|
||||
linkElement.href = googleFontsURL;
|
||||
|
||||
doc.head.appendChild(linkElement);
|
||||
}
|
||||
|
||||
function hexToRgba(hex) {
|
||||
hex = hex.replace('#', '');
|
||||
|
||||
const r = parseInt(hex.substring(0, 2), 16);
|
||||
const g = parseInt(hex.substring(2, 4), 16);
|
||||
const b = parseInt(hex.substring(4, 6), 16);
|
||||
|
||||
let opac_20 = `rgba(${r}, ${g}, ${b}, 0.2)`;
|
||||
|
||||
document.documentElement.style.setProperty('--text-color-20', opac_20);
|
||||
}
|
||||
|
||||
function getParameterByName(name, url) {
|
||||
if (!url) url = window.location.href;
|
||||
name = name.replace(/[\[\]]/g, "\\$&");
|
||||
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
|
||||
results = regex.exec(url);
|
||||
if (!results) return null;
|
||||
if (!results[2]) return '';
|
||||
return decodeURIComponent(results[2].replace(/\+/g, " "));
|
||||
}
|
||||
|
||||
function debounce(fn, delay) {
|
||||
let timerId;
|
||||
return function(...args) {
|
||||
if (timerId) {
|
||||
clearTimeout(timerId);
|
||||
}
|
||||
timerId = setTimeout(() => {
|
||||
fn(...args);
|
||||
timerId = null;
|
||||
}, delay);
|
||||
};
|
||||
}
|
||||
|
||||
let scrollPosition = 0;
|
||||
|
||||
function disableScrolling() {
|
||||
scrollPosition = window.pageYOffset;
|
||||
document.body.style.overflow = 'hidden';
|
||||
document.body.style.position = 'fixed';
|
||||
document.body.style.top = `-${scrollPosition}px`;
|
||||
document.body.style.width = '100%';
|
||||
document.documentElement.style.scrollBehavior = 'auto';
|
||||
|
||||
}
|
||||
|
||||
function enableScrolling(scrollToPosition = true) {
|
||||
document.body.style.removeProperty('overflow');
|
||||
document.body.style.removeProperty('position');
|
||||
document.body.style.removeProperty('top');
|
||||
document.body.style.removeProperty('width');
|
||||
if(scrollToPosition){
|
||||
window.scrollTo(0, scrollPosition);
|
||||
}
|
||||
document.documentElement.style.scrollBehavior = 'smooth';
|
||||
}
|
||||
|
||||
function lazyLoadImages(container = document){
|
||||
container.querySelectorAll('.hover-image-opacity figure').forEach(wrapper => {
|
||||
let img = wrapper.querySelector('img');
|
||||
if(!img) return;
|
||||
if (img.complete) {
|
||||
wrapper.classList.add("loaded");
|
||||
} else {
|
||||
img.addEventListener("load", () => {
|
||||
wrapper.classList.add("loaded");
|
||||
});
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function moveFeaturedImage(){
|
||||
let article = document.querySelector('article');
|
||||
|
||||
if(article.getAttribute('data-has-feature-image') != 'true') return;
|
||||
if(article.getAttribute('data-post-header-type') != 'Narrow') return;
|
||||
if(article.getAttribute('data-use-sidebar') != 'true') return;
|
||||
|
||||
document.querySelector('.post-content-outer').insertBefore(document.querySelector('.post-main-image-wrapper'), document.querySelector('.post-content-outer').firstChild);
|
||||
}
|
||||
|
||||
function stickySidebar() {
|
||||
let sidebar = document.querySelector('.post-sidebar');
|
||||
if(!sidebar) return;
|
||||
|
||||
var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
|
||||
sidebar.offsetHeight > viewportHeight ? sidebar.style.top = `calc(100vh - ${sidebar.offsetHeight}px)` : sidebar.style.top = 'calc(2.64vw * var(--scale))';
|
||||
}
|
||||
|
||||
function setLightense(){
|
||||
window.addEventListener('DOMContentLoaded', function () {
|
||||
const imagesInAnchors = document.querySelectorAll('.post-content a img, .post-content .kg-product-card img, .kg-signup-card img, .kg-header-card img');
|
||||
|
||||
imagesInAnchors.forEach((img) => {
|
||||
img.classList.add('no-lightense');
|
||||
});
|
||||
|
||||
Lightense('.post-content img:not(.no-lightense)', {
|
||||
background: 'var(--background-color)'
|
||||
});
|
||||
}, false);
|
||||
}
|
||||
|
||||
function setToggle() {
|
||||
const toggleHeadingElements = document.getElementsByClassName("kg-toggle-heading");
|
||||
|
||||
const svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svgElement.setAttribute("viewBox", "0 0 16 10");
|
||||
svgElement.setAttribute("fill", "none");
|
||||
svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg");
|
||||
|
||||
const pathElement = document.createElementNS("http://www.w3.org/2000/svg", "path");
|
||||
pathElement.setAttribute("d", "M16 2L8 10L-3.49691e-07 2L1.42 0.580001L8 7.16L14.58 0.58L16 2Z");
|
||||
|
||||
svgElement.appendChild(pathElement);
|
||||
|
||||
document.querySelectorAll('.kg-toggle-card').forEach(card => {
|
||||
card.querySelector('.kg-toggle-heading svg').remove();
|
||||
|
||||
const container = card.querySelector(".kg-toggle-card-icon");
|
||||
const clonedSvg = svgElement.cloneNode(true);
|
||||
|
||||
container.appendChild(clonedSvg);
|
||||
})
|
||||
|
||||
const toggleFn = function(event) {
|
||||
|
||||
const targetElement = event.target;
|
||||
const parentElement = targetElement.closest('.kg-toggle-card');
|
||||
var toggleState = parentElement.getAttribute("data-kg-toggle-state");
|
||||
if (toggleState === 'close') {
|
||||
parentElement.setAttribute('data-kg-toggle-state', 'open');
|
||||
} else {
|
||||
parentElement.setAttribute('data-kg-toggle-state', 'close');
|
||||
}
|
||||
};
|
||||
|
||||
for (let i = 0; i < toggleHeadingElements.length; i++) {
|
||||
toggleHeadingElements[i].addEventListener('click', toggleFn, false);
|
||||
}
|
||||
}
|
||||
|
||||
function copyUrlToClipboard(parentElement){
|
||||
let parent = document.querySelector(`.${parentElement}`)
|
||||
let alert = parent.querySelector('.clipboard-alert');
|
||||
|
||||
parent.querySelector('.clipboard-link').addEventListener('click', () => {
|
||||
navigator.clipboard.writeText(window.location.href);
|
||||
alert.style.display = "block";
|
||||
|
||||
setTimeout(function () {
|
||||
alert.style.display = "none";
|
||||
}, 3000);
|
||||
})
|
||||
}
|
||||
396
newspaper/assets/js/post-content.js
Normal file
396
newspaper/assets/js/post-content.js
Normal file
@ -0,0 +1,396 @@
|
||||
/* IMAGE GALLERY */
|
||||
|
||||
(function() {
|
||||
const images = document.querySelectorAll('.kg-gallery-image img');
|
||||
images.forEach(function (image) {
|
||||
const container = image.closest('.kg-gallery-image');
|
||||
const width = image.attributes.width.value;
|
||||
const height = image.attributes.height.value;
|
||||
const ratio = width / height;
|
||||
container.style.flex = ratio + ' 1 0%';
|
||||
})
|
||||
})();
|
||||
|
||||
/* VIDEO CARD */
|
||||
|
||||
(function() {
|
||||
const handleVideoPlayer = function (videoElementContainer) {
|
||||
const videoPlayer = videoElementContainer.querySelector('.kg-video-player');
|
||||
const videoPlayerContainer = videoElementContainer.querySelector('.kg-video-player-container');
|
||||
const playIconContainer = videoElementContainer.querySelector('.kg-video-play-icon');
|
||||
const pauseIconContainer = videoElementContainer.querySelector('.kg-video-pause-icon');
|
||||
const seekSlider = videoElementContainer.querySelector('.kg-video-seek-slider');
|
||||
const playbackRateContainer = videoElementContainer.querySelector('.kg-video-playback-rate');
|
||||
const muteIconContainer = videoElementContainer.querySelector('.kg-video-mute-icon');
|
||||
const unmuteIconContainer = videoElementContainer.querySelector('.kg-video-unmute-icon');
|
||||
const volumeSlider = videoElementContainer.querySelector('.kg-video-volume-slider');
|
||||
const videoEl = videoElementContainer.querySelector('video');
|
||||
const durationContainer = videoElementContainer.querySelector('.kg-video-duration');
|
||||
const currentTimeContainer = videoElementContainer.querySelector('.kg-video-current-time');
|
||||
const largePlayIcon = videoElementContainer.querySelector('.kg-video-large-play-icon');
|
||||
const videoOverlay = videoElementContainer.querySelector('.kg-video-overlay');
|
||||
let playbackRates = [{
|
||||
rate: 0.75,
|
||||
label: '0.7×'
|
||||
}, {
|
||||
rate: 1.0,
|
||||
label: '1×'
|
||||
}, {
|
||||
rate: 1.25,
|
||||
label: '1.2×'
|
||||
}, {
|
||||
rate: 1.75,
|
||||
label: '1.7×'
|
||||
}, {
|
||||
rate: 2.0,
|
||||
label: '2×'
|
||||
}];
|
||||
|
||||
let raf = null;
|
||||
let currentPlaybackRateIdx = 1;
|
||||
if (!!videoEl.loop) {
|
||||
largePlayIcon.classList.add("kg-video-hide-animated");
|
||||
videoOverlay.classList.add("kg-video-hide-animated");
|
||||
}
|
||||
const whilePlaying = () => {
|
||||
seekSlider.value = Math.floor(videoEl.currentTime);
|
||||
currentTimeContainer.textContent = calculateTime(seekSlider.value);
|
||||
videoPlayer.style.setProperty('--seek-before-width', `${seekSlider.value / seekSlider.max * 100}%`);
|
||||
raf = requestAnimationFrame(whilePlaying);
|
||||
}
|
||||
|
||||
const showRangeProgress = (rangeInput) => {
|
||||
if (rangeInput === seekSlider) {
|
||||
videoPlayer.style.setProperty('--seek-before-width', rangeInput.value / rangeInput.max * 100 + '%');
|
||||
}
|
||||
else {
|
||||
videoPlayer.style.setProperty('--volume-before-width', rangeInput.value / rangeInput.max * 100 + '%');
|
||||
}
|
||||
}
|
||||
|
||||
const calculateTime = (secs) => {
|
||||
const minutes = Math.floor(secs / 60);
|
||||
const seconds = Math.floor(secs % 60);
|
||||
const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`;
|
||||
return `${minutes}:${returnedSeconds}`;
|
||||
}
|
||||
|
||||
const displayDuration = () => {
|
||||
durationContainer.textContent = calculateTime(videoEl.duration);
|
||||
}
|
||||
|
||||
const setSliderMax = () => {
|
||||
seekSlider.max = Math.floor(videoEl.duration);
|
||||
}
|
||||
|
||||
const displayBufferedAmount = () => {
|
||||
if (videoEl.buffered.length > 0) {
|
||||
const bufferedAmount = Math.floor(videoEl.buffered.end(videoEl.buffered.length - 1));
|
||||
videoPlayer.style.setProperty('--buffered-width', `${(bufferedAmount / seekSlider.max) * 100}%`);
|
||||
}
|
||||
}
|
||||
|
||||
if (videoEl.readyState > 0) {
|
||||
displayDuration();
|
||||
setSliderMax();
|
||||
displayBufferedAmount();
|
||||
if (videoEl.autoplay) {
|
||||
raf = requestAnimationFrame(whilePlaying);
|
||||
playIconContainer.classList.add("kg-video-hide");
|
||||
pauseIconContainer.classList.remove("kg-video-hide");
|
||||
}
|
||||
if (videoEl.muted) {
|
||||
unmuteIconContainer.classList.add("kg-video-hide");
|
||||
muteIconContainer.classList.remove("kg-video-hide");
|
||||
}
|
||||
} else {
|
||||
videoEl.addEventListener('loadedmetadata', () => {
|
||||
displayDuration();
|
||||
setSliderMax();
|
||||
displayBufferedAmount();
|
||||
if (videoEl.autoplay) {
|
||||
raf = requestAnimationFrame(whilePlaying);
|
||||
playIconContainer.classList.add("kg-video-hide");
|
||||
pauseIconContainer.classList.remove("kg-video-hide");
|
||||
}
|
||||
if (videoEl.muted) {
|
||||
unmuteIconContainer.classList.add("kg-video-hide");
|
||||
muteIconContainer.classList.remove("kg-video-hide");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
videoElementContainer.onmouseover = () => {
|
||||
if (!videoEl.loop) {
|
||||
videoPlayerContainer.classList.remove("kg-video-hide-animated");
|
||||
}
|
||||
}
|
||||
|
||||
videoElementContainer.onmouseleave = () => {
|
||||
const isPlaying = !!(videoEl.currentTime > 0 && !videoEl.paused && !videoEl.ended && videoEl.readyState > 2);
|
||||
if (isPlaying) {
|
||||
videoPlayerContainer.classList.add("kg-video-hide-animated");
|
||||
}
|
||||
}
|
||||
|
||||
videoElementContainer.addEventListener('click', () => {
|
||||
if (!videoEl.loop) {
|
||||
const isPlaying = !!(videoEl.currentTime > 0 && !videoEl.paused && !videoEl.ended && videoEl.readyState > 2);
|
||||
if (isPlaying) {
|
||||
handleOnPause();
|
||||
} else {
|
||||
handleOnPlay();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
videoEl.onplay = () => {
|
||||
largePlayIcon.classList.add("kg-video-hide-animated");
|
||||
videoOverlay.classList.add("kg-video-hide-animated");
|
||||
playIconContainer.classList.add("kg-video-hide");
|
||||
pauseIconContainer.classList.remove("kg-video-hide");
|
||||
};
|
||||
|
||||
const handleOnPlay = () => {
|
||||
largePlayIcon.classList.add("kg-video-hide-animated");
|
||||
videoOverlay.classList.add("kg-video-hide-animated");
|
||||
playIconContainer.classList.add("kg-video-hide");
|
||||
pauseIconContainer.classList.remove("kg-video-hide");
|
||||
videoEl.play();
|
||||
raf = requestAnimationFrame(whilePlaying);
|
||||
}
|
||||
|
||||
const handleOnPause = () => {
|
||||
pauseIconContainer.classList.add("kg-video-hide");
|
||||
playIconContainer.classList.remove("kg-video-hide");
|
||||
videoEl.pause();
|
||||
cancelAnimationFrame(raf);
|
||||
}
|
||||
|
||||
largePlayIcon.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
handleOnPlay();
|
||||
});
|
||||
|
||||
playIconContainer.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
handleOnPlay();
|
||||
});
|
||||
|
||||
pauseIconContainer.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
handleOnPause();
|
||||
});
|
||||
|
||||
muteIconContainer.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
muteIconContainer.classList.add("kg-video-hide");
|
||||
unmuteIconContainer.classList.remove("kg-video-hide");
|
||||
videoEl.muted = false;
|
||||
});
|
||||
|
||||
unmuteIconContainer.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
unmuteIconContainer.classList.add("kg-video-hide");
|
||||
muteIconContainer.classList.remove("kg-video-hide");
|
||||
videoEl.muted = true;
|
||||
});
|
||||
|
||||
playbackRateContainer.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
let nextPlaybackRate = playbackRates[(currentPlaybackRateIdx + 1) % 5];
|
||||
currentPlaybackRateIdx = currentPlaybackRateIdx + 1;
|
||||
videoEl.playbackRate = nextPlaybackRate.rate;
|
||||
playbackRateContainer.textContent = nextPlaybackRate.label;
|
||||
});
|
||||
|
||||
videoEl.addEventListener('progress', displayBufferedAmount);
|
||||
|
||||
seekSlider.addEventListener('input', (e) => {
|
||||
e.stopPropagation();
|
||||
showRangeProgress(e.target);
|
||||
currentTimeContainer.textContent = calculateTime(seekSlider.value);
|
||||
if (!videoEl.paused) {
|
||||
cancelAnimationFrame(raf);
|
||||
}
|
||||
});
|
||||
|
||||
seekSlider.addEventListener('change', (event) => {
|
||||
event.stopPropagation();
|
||||
videoEl.currentTime = seekSlider.value;
|
||||
if (!videoEl.paused) {
|
||||
requestAnimationFrame(whilePlaying);
|
||||
}
|
||||
});
|
||||
|
||||
volumeSlider.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
});
|
||||
|
||||
seekSlider.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
});
|
||||
|
||||
volumeSlider.addEventListener('input', (e) => {
|
||||
e.stopPropagation();
|
||||
const value = e.target.value;
|
||||
showRangeProgress(e.target);
|
||||
videoEl.volume = value / 100;
|
||||
});
|
||||
}
|
||||
|
||||
const videoCardElements = document.querySelectorAll('.kg-video-card');
|
||||
|
||||
for (let i = 0; i < videoCardElements.length; i++) {
|
||||
handleVideoPlayer(videoCardElements[i]);
|
||||
}
|
||||
})();
|
||||
|
||||
/* AUDIO CARD */
|
||||
|
||||
(function() {
|
||||
const handleAudioPlayer = function (audioElementContainer) {
|
||||
const audioPlayerContainer = audioElementContainer.querySelector('.kg-audio-player-container');
|
||||
const playIconContainer = audioElementContainer.querySelector('.kg-audio-play-icon');
|
||||
const pauseIconContainer = audioElementContainer.querySelector('.kg-audio-pause-icon');
|
||||
const seekSlider = audioElementContainer.querySelector('.kg-audio-seek-slider');
|
||||
const playbackRateContainer = audioElementContainer.querySelector('.kg-audio-playback-rate');
|
||||
const muteIconContainer = audioElementContainer.querySelector('.kg-audio-mute-icon');
|
||||
const unmuteIconContainer = audioElementContainer.querySelector('.kg-audio-unmute-icon');
|
||||
const volumeSlider = audioElementContainer.querySelector('.kg-audio-volume-slider');
|
||||
const audio = audioElementContainer.querySelector('audio');
|
||||
const durationContainer = audioElementContainer.querySelector('.kg-audio-duration');
|
||||
const currentTimeContainer = audioElementContainer.querySelector('.kg-audio-current-time');
|
||||
let playbackRates = [{
|
||||
rate: 0.75,
|
||||
label: '0.7×'
|
||||
}, {
|
||||
rate: 1.0,
|
||||
label: '1×'
|
||||
}, {
|
||||
rate: 1.25,
|
||||
label: '1.2×'
|
||||
}, {
|
||||
rate: 1.75,
|
||||
label: '1.7×'
|
||||
}, {
|
||||
rate: 2.0,
|
||||
label: '2×'
|
||||
}];
|
||||
|
||||
let raf = null;
|
||||
let currentPlaybackRateIdx = 1;
|
||||
|
||||
const whilePlaying = () => {
|
||||
seekSlider.value = Math.floor(audio.currentTime);
|
||||
currentTimeContainer.textContent = calculateTime(seekSlider.value);
|
||||
audioPlayerContainer.style.setProperty('--seek-before-width', `${seekSlider.value / seekSlider.max * 100}%`);
|
||||
raf = requestAnimationFrame(whilePlaying);
|
||||
}
|
||||
|
||||
const showRangeProgress = (rangeInput) => {
|
||||
if (rangeInput === seekSlider) {
|
||||
audioPlayerContainer.style.setProperty('--seek-before-width', rangeInput.value / rangeInput.max * 100 + '%');
|
||||
}
|
||||
else {
|
||||
audioPlayerContainer.style.setProperty('--volume-before-width', rangeInput.value / rangeInput.max * 100 + '%');
|
||||
}
|
||||
}
|
||||
|
||||
const calculateTime = (secs) => {
|
||||
const minutes = Math.floor(secs / 60);
|
||||
const seconds = Math.floor(secs % 60);
|
||||
const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`;
|
||||
return `${minutes}:${returnedSeconds}`;
|
||||
}
|
||||
|
||||
const displayDuration = () => {
|
||||
durationContainer.textContent = calculateTime(audio.duration);
|
||||
}
|
||||
|
||||
const setSliderMax = () => {
|
||||
seekSlider.max = Math.floor(audio.duration);
|
||||
}
|
||||
|
||||
const displayBufferedAmount = () => {
|
||||
if (audio.buffered.length > 0) {
|
||||
const bufferedAmount = Math.floor(audio.buffered.end(audio.buffered.length - 1));
|
||||
audioPlayerContainer.style.setProperty('--buffered-width', `${(bufferedAmount / seekSlider.max) * 100}%`);
|
||||
}
|
||||
}
|
||||
|
||||
if (audio.readyState > 0) {
|
||||
displayDuration();
|
||||
setSliderMax();
|
||||
displayBufferedAmount();
|
||||
} else {
|
||||
audio.addEventListener('loadedmetadata', () => {
|
||||
displayDuration();
|
||||
setSliderMax();
|
||||
displayBufferedAmount();
|
||||
});
|
||||
}
|
||||
|
||||
playIconContainer.addEventListener('click', () => {
|
||||
playIconContainer.classList.add("kg-audio-hide");
|
||||
pauseIconContainer.classList.remove("kg-audio-hide");
|
||||
audio.play();
|
||||
requestAnimationFrame(whilePlaying);
|
||||
});
|
||||
|
||||
pauseIconContainer.addEventListener('click', () => {
|
||||
pauseIconContainer.classList.add("kg-audio-hide");
|
||||
playIconContainer.classList.remove("kg-audio-hide");
|
||||
audio.pause();
|
||||
cancelAnimationFrame(raf);
|
||||
});
|
||||
|
||||
muteIconContainer.addEventListener('click', () => {
|
||||
muteIconContainer.classList.add("kg-audio-hide");
|
||||
unmuteIconContainer.classList.remove("kg-audio-hide");
|
||||
audio.muted = false;
|
||||
});
|
||||
|
||||
unmuteIconContainer.addEventListener('click', () => {
|
||||
unmuteIconContainer.classList.add("kg-audio-hide");
|
||||
muteIconContainer.classList.remove("kg-audio-hide");
|
||||
audio.muted = true;
|
||||
});
|
||||
|
||||
playbackRateContainer.addEventListener('click', () => {
|
||||
let nextPlaybackRate = playbackRates[(currentPlaybackRateIdx + 1) % 5];
|
||||
currentPlaybackRateIdx = currentPlaybackRateIdx + 1;
|
||||
audio.playbackRate = nextPlaybackRate.rate;
|
||||
playbackRateContainer.textContent = nextPlaybackRate.label;
|
||||
});
|
||||
|
||||
audio.addEventListener('progress', displayBufferedAmount);
|
||||
|
||||
seekSlider.addEventListener('input', (e) => {
|
||||
showRangeProgress(e.target);
|
||||
currentTimeContainer.textContent = calculateTime(seekSlider.value);
|
||||
if (!audio.paused) {
|
||||
cancelAnimationFrame(raf);
|
||||
}
|
||||
});
|
||||
|
||||
seekSlider.addEventListener('change', () => {
|
||||
audio.currentTime = seekSlider.value;
|
||||
if (!audio.paused) {
|
||||
requestAnimationFrame(whilePlaying);
|
||||
}
|
||||
});
|
||||
|
||||
volumeSlider.addEventListener('input', (e) => {
|
||||
const value = e.target.value;
|
||||
showRangeProgress(e.target);
|
||||
audio.volume = value / 100;
|
||||
});
|
||||
}
|
||||
|
||||
const audioCardElements = document.querySelectorAll('.kg-audio-card');
|
||||
|
||||
for (let i = 0; i < audioCardElements.length; i++) {
|
||||
handleAudioPlayer(audioCardElements[i]);
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user