I am trying to modify a site to make it open external links in a new tab.
Currently I have a loop which works fine except that it opens ALL links in a new tab which is not desired:
I have tried using filters but can't seem to get it to work properly.
<script>
document.addEventListener('DOMContentLoaded', function(){
let links = document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
links[i].setAttribute('target','_blank');
}
});
</script>
Maybe checking if the URL contains a Shopify handle or something along the line?
Thank you in advance!
You can check if the href attributes begins with http://, https:// or www. since those are the most common external links, all internal usually starts with /. (you can add an additional check if the href contains the domain name as well since it possible to have internal URL with the full URL)
So the code will become something like so:
document.addEventListener('DOMContentLoaded', function(){
const links = document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
const link = links[i];
const href = link.getAttribute('href');
if(href.match(/^((https?:\/\/)|(www\.))/) {
link.setAttribute('target','_blank');
}
}
});
Maybe something like this?
const links = document.querySelectorAll("a"); //get all <a> elements
links.forEach(el => { //loop trought all <a> elements
if(!el.href.includes(window.location.hostname)){ //if not this domain
el.setAttribute("target", "_blank");
}
})
/*just to show elements with target=_blank*/
[target="_blank"]{
color: green
}
other domain
this domain
Note: you don't need that document.addEventListener('DOMContentLoaded'... just put defer attribute on your <script> tag
To get only External links Open in new Tabs, you must use anchor’s property hostname, when its value not matching your “localhostname” string then overwriting anchor's property target default value "_self"(current browser content) to "_blank"(new tab) value, your script code will be:
<script>
document.addEventListener('DOMContentLoaded', function(){
let links = document.getElementsByTagName('a');
for(var i=0;i<links.length;i++){
if (links[i].hostname!="localhostname"){
links[i].setAttribute('target','_blank');
}
}
});
</script>
Related
I'm new to Javascript, and need some help with creating a script that adds 'onclick' to href links of a particular class on an HTML page, upon page load - using the link's href URL, without touching the inline code. The script would modify a regular link, from this
<a href="URL" class="XYZ">
to this:
<a href="#" onclick="location.href='URL';" class="XYZ">
The URL changes for each link but the class remains the same. Here is what I got so far, but I was wondering if it can be improved:
window.onload = function() {
// Saving all links with XYZ-class in a variable
let links = document.getElementsByClassName('XYZ');
// Iterating through the links, changing the onclick attribute
for(let i = 0; i < links.length; i++) {
// Saving the URL
let grabbedURL = links[i].getAttribute('href');
// Putting it in onclick
links[i].setAttribute('onclick', `location.href='${grabbedURL}'`);
// Replacing href with '#'
links[i].setAttribute('href', '#');
}
Here's an approach using a for...of loop; you can change that if you want:
// iterate through all results of a css selector
for (let link of document.querySelectorAll('a.XYZ')) {
// set onclick attribute as text
link.setAttribute('onclick', 'location.href = ' + JSON.stringify(link.href) + ';');
// set href attribute to empty anchor (#)
link.href = '#';
}
<body>
http://example.com/
<br>
http://foo.bar/
</body>
There could be more modern solutions to your problem using EventTarget.addEventListener(), but so far that's what you requested. If you have a question to this answer please write a comment under it.
And as you new to Stack Overflow: If you had a helpful answer for your question, you can mark it as accepted. Of cause only if you want. Doesn't have to be mine.
Placing this in your JS should do it:
const convert = () => {
const links = document.querySelectorAll("a");
for(let i = 0; i < links.length; i++){
let href = links[i].getAttribute("href");
let handleClick = () => {
console.log("the url is:",href)
window.location.href = href;
}
links[i].onclick = handleClick;
links[i].setAttribute("href","#");
}
}
convert();
I think you might be missing a larger point here. An anchor is designed for navigation, if you want to change the destination, don't set an onclick and then disable the href, just update the href to where you want to go.
And, to do this in the simplest way, use event delegation, where we leverage the fact that events bubble up from their origin to the document. We just create one event handler on a common ancestor of all the elements in question and handle the even there. When we do, we check to see if the event originated at an element that we care about using event.target and if it did, we act accordingly.
Here's an example:
let url = "https://example.com";
// Set an event listener on the document itself
document.addEventListener("click", function(event){
// Check to see if the event originated at an
// element we want to handle.
if(event.target.nodeName === "A" && event.target.classList.contains("XYZ")){
// Just update the href of the element
event.target.href = url;
}
});
<p>Click the links below. Only the XYZ links will take you to example.com</p>
XYZ
abc
qrs
XYZ
zzz
XYZ
aaa
XYZ
If I'm understanding your question, I think you want something like this:
function updateLink() {
var link = document.getElementById("linkId");
link.setAttribute('href', "http://google.com");
}
Then just add an 'id' to your link. Or get the class rather than the id.
document.getElementsByClassName('XYZ')[0].setAttribute("onclick","location.href='URL' ")
Try this..
For after page load effect add script at the very end of your body tag
I am trying to find a way (JQuery etc.) of auto updating the URL for sharing on Facebook, Twitter etc.
For example:
<img src="../img/facebook.png">
Except I want to replace "http//xxxxxxxxx.co.uk" with something so that if the URL of that page were to change, it would grab that URL and insert it into the tag, without me having to update it manually?
Do you just mean that you want to dynamically build this href from the current page's URL? Something like this?:
document.getElementById('yourAnchorElement').href =
'https://www.facebook.com/sharer/sharer.php?u=' +
encodeURIComponent(window.location.href);
It just gets the current URL, URL-encodes it to be used as a query string parameter, appends it to the known base URL, and sets it to the href of the element.
You don't need to use document.getElementById(), any method you use to identify the target element is fine.
Here is a small function to generate share buttons with jQuery.
HTML
<div id="fb"></div>
jQuery
var fblink = "https://www.facebook.com/sharer/sharer.php?u={{link}}";
$(document).ready(function () {
generateLink('fb','http://www.google.com');
generateLink('fb','http://www.stackoverflow.com');
});
function generateLink(id,link) {
$('#' + id).append('Share');
}
JSFiddle
I replaced you image with "Share" for completeness in JSFiddle without access to your image, but that can be replaced to suit your needs.
Using jQuery you can do something like this on document.ready:
Here is a jsFiddle demo
$(function () {
var fbShare = 'https://www.facebook.com/sharer/sharer.php?u='
// grab url of the page:
var url = window.location;
// loop through all elements with class 'button--facebook' and update href:
$('.button--facebook').each(function () {
$(this).attr('href', fbShare + url);
});
});
I tried with this code but, didn´t worked.
<a href="http://altodesign.pt/#portfolio" onClick="loadintoIframe('myframe,'portfolio/mmteam.html');">
you can try something like this
a href="javavcipt:document.getElementById('myframe').src = 'portfolio/mmteam.html';"
I would never use javascript ...
I have had a look into your webpage (plenty to learn, like add scripts to the end of the page, create a global javascript object to hold all website actions, etc ... but that's not the question)
I could see that, even thought you jump to #CONTACTOS you are not making the use of the hash at all... and you should!
using the hash would let you do things like:
http://altodesign.pt/#portfolio-cooptaxis
and that would jump to portfolio anchor and load the cooptaxis.html into the iframe and you stoped using javascript:loadintoIframe('myframe', 'portfolio/mmteam.html') at all, as that will cause Google Analytics and Crawlers not to follow up your links for example ...
your method could be something simple like
$(function() {
// let's see if we have an hash on the page
var hash = document.location.hash;
if(hash.length > 0) {
if(hash.instr('-') >= 0) {
// supposing will have only one char '-'
var img = hash.split('-')[1];
// let's remove the frame info from the hash
hash = hash.split('-')[0];
// there's a call to load into the iframe, let's load it
$("#myframe").attr("src", "portfolio/" + img + ".html")
}
// let's fly
jumpTo(hash);
}
// let's disable the anchor links by default and use the hash
$("a[href^=#]").click(function() {
// for all links that start with the hash, let's...
document.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function() {
// everytime the hash changes let's fly
jumpTo(document.location.hash);
});
});
function jumpTo(anchor) {
var a = $("a[name='" + anchor.replace('#','') + "']"),
pos = 0;
if(a.length > 0) {
// we have found the anchor, let's grab it's top position
pos = a.position().top;
}
// if we got here and pos === 0, we did not found the anchor
// for the given hash... maybe the user is playing around ...
// and we shall fly
$('body,html').animate({
scrollTop: pos
}, 800);
}
justthis will allow you to avoid using javascript to jump your links, as all they now have to have is simple: Portfolio
Let we say that you have page1.html in-which a link to page2.html you want it to be opened in an iframe in page1.html
in page1.html
link
<iframe name="iframe-name"></iframe>
Then you are able to add any anchor you want. It is just a matter of naming your iframe and then targeting it in the link!
I'm creating a FF addon. I want to block all the URLs with .jpg (or any other user defined extension) in a page.
How to do it??
Presuming by URLs, you mean <a> elements, then the following code would remove all jpg/gif/png links which end with those extensions. If you wish to change it to images, you can change the elements that are searched from a to img, and change the search test from href to src.
Example on jsfiddle.
var m = document.getElementsByTagName("a");
var patt = new RegExp("^https?://(?:[a-z\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$","i");
var removed = 0;
for (i=0; i<m.length;){
if (patt.test(m[i].href)){
// it got matched, remove it
m[i].parentNode.removeChild(m[i]);
removed++;
}else{
i++;
}
}
alert(removed+" image url's removed");
Is there a way (I assume it would be with javascript) that I can have a checkbox or link on my page that will make all the links on my page have target="_blank"?
I want to have a checkbox that says something like "Open all links in new page/tab" on my site that when checked will change the target and unchecked will put it back to how it was.
jQuery example
$(function() {
$('#yourCheckoxId').toggle(function() {
$('a').attr('target', '_blank');
},
function() {
$('a').removeAttr('target');
});
});
You might want to try jQuery as an alternative to genuine Javascript
the actual code could look something like that:
$('a').attr(target, '_blank')
Modifying the target attribute of all the anchors on the page is merely a matter of getting all links, and setting their target properties one by one:
var anchors = document.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i++) {
anchors[i].target = '_blank';
}