I have a wordpress-website with section scrolling enabled and added 2 buttons that should jump to the previous or the next page on the website and 2 buttons that should jump to the previous or next chapter on the website.
based on this post Goto Next Anchor Button I added the script but the browser returns the length = 0 for anchors, document.getElementByTagName() returns an array that is to big
and document.getElementByName() didn't work too.
var anchordivs = document.querySelectorAll('[data-anchor][data-id]');
var anchors = anchordivs.length;
var loc = window.location.href.replace(/#.*/,'');
var nextAnchorName = 0;
var anchorName = window.location.hash.replace(/#/,'');
if (anchorName){
for (var i=0, iLength=anchordivs.length; i<iLength; i++) {
if (anchordivs[i].dataset.anchor == anchorName) {
nextAnchorName = anchordivs[i+1 % iLength].dataset.anchor;
break;
}
}
}
if (!nextAnchorName){
nextAnchorName=anchordivs[0].dataset.anchor;
}
window.location.href = loc + '#' + nextAnchorName;
}
On button click the site should scroll to the next section of the website.
EDIT: wordpress did create the anchors as data-anchors in the respective divs:
<div ... data-anchor="c_home">. Here is what still does not work. On clicking the button the site does not jump to the new anchor and manually entering a anchor in the adressline of the browser does not work either. The JS-Code is tested and works now.
Maybe the problem for the missing jump is that it is all on one page?
I got it working by changing the last codeline to the following:
location.href ='#' + nextAnchorName;
location.reload();
Now its reloading the site with each click, but it works. That is not what i want.
I changed var anchors = document.body.getElementsByTagName("a"); and nextAnchorName = anchors[i++ % iLen].name;
function goToNextAnchor() {
var anchors = document.body.getElementsByTagName("a");
var loc = window.location.href.replace(/#.*/,'');
var nextAnchorName;
// Get name of the current anchor from the hash
// if there is one
var anchorName = window.location.hash.replace(/#/,'');
// If there is an anchor name...
if (anchorName) {
// Find current element in anchor list, then
// get next anchor name, or if at last anchor, set to first
for (var i=0, iLen=anchors.length; i<iLen; i++) {
if (anchors[i].name == anchorName) {
nextAnchorName = anchors[i++ % iLen].name;
break;
}
}
}
// If there was no anchorName or no match,
// set nextAnchorName to first anchor name
if (!nextAnchorName) {
nextAnchorName = anchors[0].name;
}
// Go to new URL
window.location.href = loc + '#' + nextAnchorName;
}
Related
On my site, I have some links that are built dynamically with JS. Not all of them contain an href value, so I add an href value dynamically. I use javascript:; as that value.
Now, I need to be able to open all links not on my host in a new window. Obviously, javascript:; is not my host, so any link with that in the href attribute will open in a new window.
In the snippet below, I'm trying to prevent that from happening, but I'm not getting the result I desire.
How do I push all offsite links to a new tab, except for one that I specify?
document.querySelectorAll("a:not(a[href])").forEach(element => {
element.setAttribute("href", "javascript:;")
});
var all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++) {
var a = all_links[i];
if (a.hostname != location.hostname || a.getAttribute("href") !== 'javascript:;') {
a.rel = 'noopener';
a.target = '_blank';
}
}
Yahoo!
<hr>
<a>something else</a>
Looks like this was the best solution...
If you inspect each link, you'll see that the external link has _blank, the internal link has _self, and the one with href="javascript:;" has _self.
document.querySelectorAll("a:not(a[href])").forEach(element => {
element.setAttribute("href", "javascript:;")
});
let all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++) {
let anchors = all_links[i];
if (anchors.getAttribute('href') == 'javascript:;' || anchors.hostname == location.hostname) {
anchors.target = "_self";
} else {
anchors.target = "_blank";
}
}
External Link (Yahoo!)
<hr>
Change the font and the line spacing of a style (SO Question)
<hr>
<a>anchor without href (Goes nowhere)</a>
I start with a button that activates the function onclick:
<button onclick="openStuff();">Click here!</button>
Then, I have an array of links like so:
var links = [
"msn.com",
"google.com",
"youtube.com",
"bbc.com",
"facebook.com",
"cnn.com",
"fox.com",
"techcrunch.com"];
Finally, I define the function that randomly applies a link to the button from the above array:
openStuff = function () {
// get a random number between 0 and the number of links
var randIdx = Math.random() * links.length;
// round it, so it can be used as array index
randIdx = parseInt(randIdx, 10);
// construct the link to be opened
var link = 'https://' + links[randIdx];
// open it in a new window / tab (depends on browser setting)
window.open(link);
};
The problem is I need it to not be random. Rather, I need it to go down the list sequentially as the user clicks the button. If the user clicks the button once it should go to the first link. But, if this user clicks the button a second time it should go to the second link in the list.
For example: User clicks button: Go to first link, User clicks button again: go to second link, and so on.
var linkIndex = 0;
openStuff = function () {
//when no more links are available to click then return
if(links.length <= linkIndex) return;
// construct the link to be opened
var link = 'https://' + links[linkIndex];
// open it in a new window / tab (depends on browser setting)
window.open(link);
linkIndex++;
};
You need a global index that start in 0. Then, inside the function you increment it after open the link.
var link = 'https://' + links[index];
index++;
I would do it like this:
var special_button_state = 0;
const links = [
"msn.com",
"google.com",
"youtube.com",
"bbc.com",
"facebook.com",
"cnn.com",
"fox.com",
"techcrunch.com"
];
const openStuff = function () {
var link = 'https://' + links[special_button_state];
if(special_button_state < links.length-1) {
special_button_state++;
}
window.open(link);
console.log(link);
};
<button onclick="openStuff();">Click here!</button>
You could have another variable set to the first index of the array, something like:
var linkTarget = 0
and then update linkTarget in the function to increment appropriately:
openStuff = function () {
// construct the link to be opened
var link = 'https://' + links[linkTarget];
// open it in a new window / tab (depends on browser setting)
window.open(link);
// update the index
if (linkTarget++ == links.length)
linkTarget = 0
};
You could also implement a dynamic label so that you know where it's going:
<body onload="setLink()">
<button id="turntable-button" onclick="openStuff()" />
</body>
Label setter on page load (put the same getElementById() line in openStuff() after updating the index):
setLink = function() {
document.getElementById("turntable-button").innerHTML = links[linkTarget];
}
I've created a loader for my website (the whole front end is custom,so as of right now i can edit about 95% of everything I have except for woocommerce plugin).
Super simple one, it follows this logic, if the anchor is an # or the page itself it wont do anything (which is what I wanted) but the woocommerce plugin to generate my image gallery is a link that isn't the page itself or a #. Which means I need to collect the path-name of the extension that if it ends on jpg png or any image file to continue; and skip over the rest of the animation and allow the plugin to run its course.
Ive use Barba JS, SWUP and other animations with woocommerce and this is the only one that doesnt interrupt or have so many conditions with woocommerce.
function fadeInPage() {
if (!window.AnimationEvent) { return; }
var fader = document.getElementById('fader');
fader.classList.add('fade-out');
}
document.addEventListener('DOMContentLoaded', function() {
if (!window.AnimationEvent) { return }
var anchors = document.getElementsByTagName('a');
******* for (var idx = 0; idx < anchors.length; idx += 1) {
if (anchors[idx].hostname !== window.location.hostname || anchors[idx].pathname === window.location.pathname) *******
{
continue;
}
anchors[idx].addEventListener('click', function(event) {
var fader = document.getElementById('fader'),
anchor = event.currentTarget;
var listener = function() {
window.location = anchor.href;
fader.removeEventListener('animationend', listener);
};
fader.addEventListener('animationend', listener);
event.preventDefault();
fader.classList.add('fade-in');
});
}
});
window.addEventListener('pageshow', function (event) {
if (!event.persisted) {
return;
}
var fader = document.getElementById('fader');
fader.classList.remove('fade-in');
});
I starred what i need changed. the animation works, the page transition works. I need the animation to recognize if the a tag ends with an jpg or png to skip and not do the animation and treat the link as if the animation wasn't there.
Never used woocommerce so I don't totally understand the use case, but you can get the file extension of a link like so:
for (var idx = 0; idx < anchors.length; idx += 1) {
let fileType = anchors[idx].href.split('.').pop();
//Do whatever
}
Or if you want to compare it to a preset list of extensions you can use a regex:
for (var idx = 0; idx < anchors.length; idx += 1) {
if (anchors[idx].href.match(/\.(jpg|png)$/)) {
//Do whatever
}
}
I'm trying to create a function where, on every button click, the ID at the end of the pages URL is added to by 1. So,
example.org/page -> (buttonclick) -> example.org/page#1 -> (buttonclick) -> example.org/page#2 etc. etc.
What I've got at the moment is:
var anchor = 0;
$('#bottom-right').click(function() {
var anchor += 1;
var anchorurl = "#" + anchor;
var currenturl = window.location.href;
var newurl = currenturl.slice(0, -1) + anchorurl;
window.location.replace(newurl);
});
But it doesn't really work & I imagine there is a cleaner solution...
Thanks in advance.
simply make it
$('#bottom-right').click(function() {
window.location.hash = ++anchor;
});
Make use of the built-in hash method.
So basically the url contains #.So you can also track this # and get the next number and increment it.
Code example:
var hashValue = window.location.href.substring(window.location.href.indexOf('#')+1);
window.location.hash = hashValue + 1;
We have an internal inventory at work that is web based. I am looking at add a link say under a link on the page. There is no ID, or classes for me to hook into. Each link at least that I want to add something below it, starts with NFD. I basically need to pull the link text (not the link itself the text that appears to the end user) and use that in my url to call a web address for remoting in.
var links = document.evaluate("//a[contains(#href, 'NFD')]", document, null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i=0; i < links.snapshotLength; i++)
{
var thisLink = links.snapshotItem(i);
newElement = document.createElement("p");
newElement = innerHTML = ' Remote';
thisLink.parentNode.insertBefore(newElement, thisLink.nextSibling);
//thisLink.href += 'test.html';
}
Edit:
What I am looking for basically is I have a link NFDM0026 I am looking to add a link now below that using the text inside of the wickets so I want the NFDM0026 to make a custom link to call url using that. Like say a vnc viewer. The NFDM0026 changes of course to different names.
Here's how to do what you want (without jQuery; consider adding that wonderful library):
//--- Note that content search is case-sensitive.
var links = document.querySelectorAll ("a[href*='NFD']");
for (var J = links.length-1; J >= 0; --J) {
var thisLink = links[J];
var newElement = document.createElement ("p");
var newURL = thisLink.textContent.trim ();
newURL = 'http://YOUR_SITE/YOUR_URL/foo.asp?bar=' + newURL;
newElement.innerHTML = ' Remote';
InsertNodeAfter (newElement, thisLink);
}
function InsertNodeAfter (newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
parent.appendChild (newElement);
else
parent.insertBefore (newElement, targetElement.nextSibling);
}