html/javascript: Hiding link destination and opening link in new tab - javascript

I am using the following javascript (provided by m59 in this previous answer) to hide the destination of a link which usually shows up at the bottom of the browser window when hovering over a link:
<div>
<a data-href="http://www.google.com/"> LINK </a>
<script type="text/javascript">
var anchors = document.querySelectorAll('a[data-href]');
for (var i=0; i<anchors.length; ++i) {
var anchor = anchors[i];
var href = anchor.getAttribute('data-href');
anchor.addEventListener('click', function() {
window.location = href;
});
}
</script>
</div>
This works perfectly fine, but I would like the link to open in a new tab as well. How do I have to change the script in order to do so?
I tried using window.open('href','_blank'); instead of window.location = href; which did not work.

Unless im missing something, the most obvious thing to do is add a target to that anchor:
<a data-href="http://www.google.com/" target="blank"> LINK </a>

This is how to do it (try it on your code, stackoverflow blocks new tabs and links)
var anchors = document.querySelectorAll('a[data-href]');
for (var i=0; i<anchors.length; ++i) {
var anchor = anchors[i];
var href = anchor.getAttribute('data-href');
anchor.addEventListener('click', function() {
window.open(href,'','');
});
}
<div>
<a data-href="http://www.google.com/"> LINK </a>
</div>

You can see here, that syntax of window.open is:
var window = window.open(url, windowName, [windowFeatures]);
So to open link in new tab you should use something like:
var myNewTab = window.open(url, '_blank');
It will not work if you window is opened as '_blank'

Did you try window.open(href)?
i.e. In your example, href is a string (there are single quotes around it) as opposed to a variable.

Why not just use an onclick event handler to redirect the user?
link
function onClick(e) {
e.preventDefault();
document.location.href='www.google.ca';
}

Related

How to change rel of the anchor in the page when href contains specific keywords

I have an affiliate related blog which means that Google wants all of my affiliate links to be marked as sponsored links with rel = "sponsored".
Not all of the links on my website are affiliate links so I only would like to trigger the script below when a href on the page contains specific keywords.
Let's say I have 3 types of affiliate href links.
abc178.com/ref=xyz
qrs221.com/ref=xyz
xyz952.com/ref=xyz
I only want this sript to run when 'abc', 'qrs' and 'xyz' is found in a href
<script type='text/javascript'>
function myFunction() {
var x = document.getElementsByTagName("a");
var i;
for (i = 0; i < x.length; i++) {
if (location.hostname!=x[i].hostname){
x[i].rel = "sponsored";
x[i].target = "_blank";
x[i].title = "Click to open in new window";
}}}
mft=setTimeout("myFunction()",0);
function LoadEvent(func){
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func;
}
else{
window.onload = function()
{
if(oldonload)
{oldonload();}
func();}}}
LoadEvent(function(){
myFunction();
});
</script>
I'm no programmer, but I suppose this is possible?
window.addEventListener('load', function(){
// make sure dom elements are rendered before sc run
let keywords = ['abs', 'qrs', 'xyz'];
document.querySelectorAll('a').forEach(anchor=>{
// iterate all anchor tags in dom
let href = anchor.getAttribute('href');
let flag = false;
keywords.forEach(kw=>{
if(href.includes(kw)){
flag = true;
}
});
if(flag){
anchor.setAttribute('rel', 'sponsored');
anchor.setAttribute('target', '_blank');
// anchor.innerHTML = 'Click to open in new window';
}
});
});
I totally understand how confusing those url references are: href, link, rel, src, hostname, location, especially for frontend beginners. however, those are essential conventions to adopt to build more flexible and sophisticated application.
I would say a simple way to remember,
href always refer to a anchor tag.
src indicates image or script url.
window.location and window.hostname are the current page url.
if the script above, I am trying to iterate all anchor tags, check if any's href contains the keywords, if so, overwrite their rel to sponsored and target to _blank (if you want to change the content text, do not use title, use innerHTML) instead.
here are some useful resources:
a
innerHTML

web page redirect javascript

I dynamically create a link to a. 'mywebsite' is a variable. Everything works but the mywebsite page replaces that of the code. I want to open mywebsite in another page.
May I have a help to solve the problem ?
var mylink = document.createElement("a");
var textForButton = document.createTextNode("More details");
mylink.appendChild(textForButton);
mylink.setAttribute("href", mywebsite);
document.body.appendChild(mylink);
You should set the linke target as this:
mylink.setAttribute("target", '_blank');
Your code my be something like this
<script>
window.onload = function () {
let mywebsite = "http://www.google.com";
var mylink = document.createElement("a");
var textForButton = document.createTextNode("More details");
mylink.appendChild(textForButton);
mylink.setAttribute("href", mywebsite);
mylink.setAttribute("target", '_blank');
document.body.appendChild(mylink);
};
</script>
You can set target=_blank attribute to do this.
mylink.setAttribute("target", "_blank");
So that once you click on the link that you have generated it opens in new tab.

Script to open sequential links each time you click the button

I got a script that opens links randomly ... but I needed to know how I create a script to open a link by myself and then return to the initial one. Eg... Click on the button and it opens link1. Click it again and it opens link2 ... again and opens link3 .... then opens link4 .... and then opens link1 again.
I'm using this script to make him open the link randomly .... but I need it to be sequential and after opening the last link he opens link1 again. Can you help me guys?!
Best regards!
Alex.
<script>
<! -
/ *
Random Links Button
* /
// Specify the links to work at random below. You can enter as many as needed
var randomlinks=new Array()
randomlinks[0]="https://website1.com"
randomlinks[1]="https://website2.com"
randomlinks[2]="https://website3.com"
randomlinks[3]="https://website4.com"
function randomlink(){
window.location=randomlinks[Math.floor(Math.random()*randomlinks.length)]
}
// - END OF SCRIPT-
</script>
You should be able to modify a global variable, which acts as a click counter, from within the function. eg:
var randomlinks=new Array();
randomlinks[0]="https://website1.com"
randomlinks[1]="https://website2.com"
randomlinks[2]="https://website3.com"
randomlinks[3]="https://website4.com"
var i=0;
function clickroundrobin(e){
if( i >= randomlinks.length )i=0;
var url=randomlinks[i];
i++;
window.location=url;
}
To test:
var randomlinks=new Array();
randomlinks[0]="https://website1.com"
randomlinks[1]="https://website2.com"
randomlinks[2]="https://website3.com"
randomlinks[3]="https://website4.com"
var i=0;
function clickroundrobin(e){
if( i >= randomlinks.length )i=0;
var url=randomlinks[i];
i++;
//window.location=url;
alert( url )
}
<a href='#' onclick='clickroundrobin(event)'>Click</a>
You can do this using window.open and by iterating the variable value on the button and pass the it as array index
<button onclick="randomlink()" >Random Link</button>
<script>
Links = []
Links.push("https://alloytech.wordpress.com");
Links.push("https://www.google.com/");
Links.push("https://www.youtube.com/");
Links.push("https://www.stackoverflow.com/");
var randomParam=0;
function randomlink() {
randomParam = randomParam >= Links.length?0:randomParam;
window.open(Links[randomParam],'popUpWindow','height=400,width=800,scrollbars=yes');
randomParam++;
}
</script>
I think this is what you are expecting

How to stay in a tab while opening a new one (open a file)?

I have a link to open a pdf in a browser. But, It gets focused on the new tab (the tab with the pdf. How to prevent this behavior?
This is the link:
<strong><a style="text-decoration:none" class='row_link' href='javascript:void(0)' target="_blank" onFocus="false">Open File</a></strong>
This is the jquery:
$("#myTable tbody").on('click','.row_link', function(e) {
var no_s = $(this).find('.filename').val().replace(/\//g , '');
var b_url = $('#base_url').val()+"assets/uploads/file/";
var url = b_url + no_s;
window.open(url);
});
I've tried adding onfocus="false" in the anchor. But, It's no effect
<html>
<strong><a style="text-decoration:none" class='row_link' href='https://github.com/caiyongji' onclick="window.open('#','_blank');window.open(this.href,'_self');">Open File</a></strong>
</html>
This effect is called the "pop under".
Basically you need to use window.blur() on the newly opened window to lose the focus and then refocus on your existing tab.
$("#myTable tbody").on('click','.row_link', function(e) {
var no_s = $(this).find('.filename').val().replace(/\//g , '');
var b_url = $('#base_url').val()+"assets/uploads/file/";
var url = b_url + no_s;
var newWindow = window.open(url);
newWindow.blur();
window.focus();
});
Relevant Stackoverflow post
If I understand correctly, what you need is, you don't want to show the newly opened tab to the user. This cannot be done as #Rex suggested, but what can be done as an alternative is, you can open a popup window and minimise it as soon as you want..
Please have a look on below code :
Parent Page
Click to open popup
Child Page
<body onLoad="setTimeout('window.blur()', 1000);"
onFocus="setTimeout('window.blur()', 1000);">
You can change the time 1000 to what you want.
You can use this on child to keep focus on parent page
window.parent.opener.focus();
Since you want the behaviour of opening background tabs, try the following code which is an example from this answer
For example in your jquery;
$("#myTable tbody").on('click','.row_link', function(e) {
var no_s = $(this).find('.filename').val().replace(/\//g , '');
var b_url = $('#base_url').val()+"assets/uploads/file/";
var url = document.createElement("a");
url.href = b_url + no_s;
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
a.dispatchEvent(evt);
});
Let me know if it helps or if you find a problem

How to open a link in a new window and also in a new tab/window with right click?

I have a help link. If a user clicks on it, it opens a new window with fixed width and height. It's working well except that when I right click the link, there is either no options to 'open in a new tab' (in IE) or I can open in a new tab but is directed to an empty page (chrome). Can any one help to make this like a link and also by default open in a new window (not a tab)?
<html>
<head>
<title>
link
</title>
<script type="text/javascript">
function activateHelpView(helpUri) {
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
(helpWindow).focus();
}
}
</script>
</head>
<body>
<a id='PortOrderPageLearnMoreLink' href='javascript:' title='Learn more' onclick='activateHelpView("http://stackoverflow.com/")'>Learn more</a>
</body>
</html>
Use a real link, not the empty javascript: address. The onclick handler can prevent the link from doing anything "normal", but you'll have something for the right-click to work with.
target=_blank is a strong hint that you want the page opened in a new window, but whether that's honored at all -- and whether in a window or a tab -- is out of the page's control.
<script type="text/javascript">
function activateHelpView(helpUri) {
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
(helpWindow).focus();
}
}
</script>
<a id='PortOrderPageLearnMoreLink' href='http://stackoverflow.com/' title='Learn more' onclick='activateHelpView(this.href); return false;' target='_blank'>Learn more</a>
A more modern way of handling all of this -- particularly if there will be more than one help link -- is to add a class to all of them, and run some JavaScript to add the click handler to each in turn. The HTML stays clean (and with real links, still works if JavaScript is disabled or not loaded).
var helplinks = document.querySelectorAll('.helplink');
for (var i = 0; i < helplinks.length; ++i) {
helplinks[i].addEventListener('click', activateHelpView);
}
function activateHelpView(event) {
event.stopPropagation(); // don't let the click run its course
event.preventDefault();
var helpUri = this.href; // "this" will be the link that was clicked
var WindowId = 'SomeWindowId';
var helpWindow = window.open(helpUri, WindowId, 'width=400,height=500,menubar=no,status=no,scrollbars=no,titlebar=no,toolbar=no,resizable=yes');
if (helpWindow) {
helpWindow.focus();
}
}
<a id='PortOrderPageLearnMoreLink'
href='http://stackoverflow.com/' title='Learn more'
class='helplink' target='_blank'>Learn more</a>
StackOverflow snippets aren't allowed to use some of these functions. A working example can be found here.

Categories