I am trying to create secondary shortcut links for a primary link, so it would be easy to (indirectly) click this link along a very long webpage, instead of scrolling up to the top of the page or click CTRL + Home every time.
I select the link to which I try to create shortcuts this way:
document.querySelector('#block-olivero-primary-local-tasks > div.block__content > nav > ul > li:nth-child(2) > a')
A shortcut link should be created alongside any heading. I create the shortcut links this way:
I have tried to listen to a click event on one of the shortcut links for the sake of triggering a pseudo-click the primary link, as follows, but I failed.
One try
document.querySelectorAll('chapterEditLink').addEventListener("click", goToEditMode() {
document.querySelector('#block-olivero-primary-local-tasks > div.block__content > nav > ul > li:nth-child(2) > a').click();
});
Another try
document.querySelectorAll('chapterEditLink').forEach((link)=>{
link.addEventListener("click", goToEditMode);
});
function goToEditMode() {
document.querySelector('#block-olivero-primary-local-tasks > div.block__content > nav > ul > li:nth-child(2) > a').click();
};
Hello ! It’s from my own personal website and appears to the only registered user (me)
I think I found out what the problem is — I lacked an href attribute in the created links.
I need to find a way to make their href identical to the url of the button with that long CSS selector I showed above (yes, it’s the correct long selector).
What caused the created shortcut links not to work was the lack of href for the links when creating them (my mistake, I omitted it myself from the original code by @PaulOB).
I have used the selector of the edit button to give the same URL to all the shortcut links.
The full code that worked for me is:
let editButton = document.querySelector('#block-olivero-primary-local-tasks > div.block__content > nav > ul > li:nth-child(2) > a').href;
console.log(editButton);
const aTag = [];
const allHs = document.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach((heading, index) => {
aTag[index] = document.createElement("a");
aTag[index].classList.add('chapterEditLink');
aTag[index].innerHTML = "Edit this chapter";
aTag[index].href = editButton;
heading.after(aTag[index]);
});
document.querySelectorAll('chapterEditLink').forEach((link)=>{
link.addEventListener("click", goToEditMode);
});
function goToEditMode() {
document.querySelector('#block-olivero-primary-local-tasks > div.block__content > nav > ul > li:nth-child(2) > a').click();
};