sbgg.jetzt/page/start/copylink.js

95 lines
2.1 KiB
JavaScript

"use strict";
window.addEventListener("load", function(event){
// REGISTER ONCLICK HANDLERS //
// iterate over all copylink buttons
let copylink_button_list = document.getElementsByClassName("copylink");
for(let one_copylink_button of copylink_button_list){
// register onclick function
one_copylink_button.onclick = function(){ copylink_click(this) };
// add descriptive title
one_copylink_button.title = copylink_hint_text;
}
});
/**
* CALLBACK: Copylink was clicked.
*
* @param self Copylink button element.
*/
async function copylink_click(self){
let success = true;
// RETRIEVE SECTION ID //
// try to find
let section_id = copylink_section_id(self);
// check whether search was successful
if(section_id === null) success = false;
// SAVE SECTION LINK TO CLIPBOARD //
if(success){
// build url
let section_url = new URL("#" + section_id, window.location.href);
// save to clipboard
try {
await navigator.clipboard.writeText(section_url);
} catch (error){
success = false;
}
}
// FEEDBACK //
if(success){
// positive feedback
self.classList.add("ti-check", "feedback-positive");
self.classList.remove("ti-link");
setTimeout(function(){
self.classList.add("ti-link");
self.classList.remove("ti-check", "feedback-positive");
}, 2500);
return;
}
// negative feedback
self.classList.add("ti-x", "feedback-negative");
self.classList.remove("ti-link");
setTimeout(function(){
self.classList.add("ti-link");
self.classList.remove("ti-x", "feedback-negative");
}, 2500);
}
/**
* HELPER: Find closest section id.
*
* @param self Base element.
*
* @return `null`: Unable to find a section id
* string: Closest section id to copylink button.
*/
function copylink_section_id(self){
// CHECK FOR ID ATTRIBUTE //
if(self.id !== undefined && self.id !== null && self.id.length > 0){
// found an id
return self.id;
}
// STOP SEARCHING //
// check whether element has parent
if(self.parentElement === null || self.parentElement === undefined) return null;
// CONTINUE SEARCHING //
return copylink_section_id(self.parentElement);
}