jQuery add target="_blank" for outgoing link - javascript

I need some help to create jquery script :)
I have some of link like this on my HTML.
Google
Home
Home
Contact Us
And now i want jQuery to check all of the link on my page. if that link is outside of my server (my server is gusdecool.com). Then add target="_blank". and the result will be like this
Google
Home
Home
Contact Us

assuming that all external links will start with http:// you could do this:
$('a[href^="http://"]').not('a[href*=gusdecool]').attr('target','_blank');

$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
$(this).attr("target","_blank");
}
});
This was from css-tricks.com, seems to work pretty well.

$('a[href^=http]:not([href^=http://www.gusdecool.com/])').attr('target','_blank');
Of course, this works only if all the external links start with the http protocol. You should adapt this code to suite your needs (suchs as links without protocols, or with different protocols).
UPDATE :
$('a[href^=http]:not([href^=http://www.gusdecool.com],[href^=http://gusdecool.com])')
.add('a[href^=www]:not([href^=www.gusdecool.com])')
.attr('target','_blank');
It selects all the a elements that have their href attribute starting with a web page address (with or without protocol) and do not point to your site's address and changes their target attribute to _blank.

This function seems to be easier if you have a subdomain:
$('a').attr('target', function() {
if(this.host == location.host) return '_self'
else return '_blank'
});

jQuery(document).ready(function(){
target_luar();
});
function target_luar(){
try{
if(top.location != location) {
jQuery("a[href^='http']")
.not("[href*='"+location.host+"']")
.attr('target','_blank');
}
} catch(err) { }
}
Demo : Demo jQuery External Link

Global function to open external links in a new window:
$(function(){ // document ready
$("a").filter(function () {
return this.hostname && this.hostname !== location.hostname;
}).each(function () {
$(this).attr({
target: "_blank",
title: "Visit " + this.href + " (click to open in a new window)"
});
});
});

Putting it all together we get the following.. Wait for it all to load, select only links starting with http or https, check if the link point to the same domain (internal) or another domain (external), add appropriate target if match found..
$(window).load(function() {
$('a[href^="http"]').attr('target', function() {
if(this.host == location.host) return '_self'
else return '_blank'
});
});

You could use jQuery's $.each function to iterate over all Anchor tags, perform the needed check and set the "target" attribute using $(this).attr("target","_blank");
Example (Not tested but should work):
$('a').each(function(index) {
var link = $(this).attr("href");
if(link.substring(0,7) == "http://")
$(this).attr("target", "_blank");
});
Shai.

Here's a fiddle demonstrating an answer using raw JS (not jQuery): http://jsfiddle.net/Xwqmm/
And here's the code:
var as = document.getElementsByTagName('a');
var re = /^https?:\/\/([^\/]*)\//;
for (var i = 0, l = as.length; i < l; i++) {
var href = as[i].href;
var matches = href.match(re);
if (matches[1] && matches[1] != "gusdecool.com") {
as[i].setAttribute("target","_blank");
}
}

This is such a brilliant site I learned so much from it :
If you do it this way you do not need to worry about http or https (handy while developing)
$('a[href^="http"]')
.not('a[href*='+ location.hostname +']')
.attr('target','_blank');

You can see all external link whith http and https
jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").each(function() {
console.log(jQuery(this).attr('href'))
});
And you can add _blank like this
jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").attr('_target','blank');

You could use filter -
$("a").filter(function () {
return this.indexOf('http://') > -1 && this.indexOf('gusdecool') == -1
}).attr("target","_blank");

Check each linkobject $(link).attr("href"), if that starts with http:// then its an outgoing link (?). Then assign the .attr("target", "_blank").
$(a).function(){
if($(this).attr("href").substring(0,3) == "http" && <!-- CHECK ITS NOT YOUR SITE URL -->){
$(this).attr("target", "_blank");
}
};
Hope this helps.

Try:
$('a[href^="http://"]')
.not('a[href*='+ location.hostname +']')
.attr('target','_blank');

<div id="myLinks">GoogleHomeHome
Contact Us</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#myLinks a').attr('target', '_blank');
});
</script>

Related

How can I add the current url parameters to the href of an <a> when clicking link to external site

we use instapage as a tool for landing pages and they strip url parameters from links if users click on tags with external links. I want to preserve the location.search though.
I tried using this script here, but it doesn't work at all - as in, the parameters still get removed unless they are specified in the href link.
window.addEventListener("click", function(e) {
var href = e.target.getAttribute("href");
if(href) {
location.href = href + window.location.search;
e.preventDefault();
}
});​
Anything obvious I am missing here?
I solved the issue by just modifying the hrefs on page load instead of trying to add the parameters onClick. Here is the code - also respecting urls that already have parameters in them.
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelectorAll('[href^="http"]').forEach((element) => {
var hrefString = element.getAttribute('href')
if(hrefString.includes('?')) {
element.setAttribute('href', hrefString + window.location.search.replace('?', '&') )
} else {
element.setAttribute('href', hrefString + window.location.search)
}
})
});

Can someone correct me

Can someone correct this code for me:
Missing ) after argument list.
<script>
$(document).ready(function() {
$("a").each(function() {
var i = $(this).attr("href");
var n = i.replace(http://www.pantsumation.com, "https://www.pantsumation.com");
$(this).attr("href", function() {
return n
})
})
});
</script>
Thank you, im not that good at javascript and just starting out.
Probably you need to add quotes around the first URL, like so:
$(document).ready(function() {
$("a").each(function() {
var i = $(this).attr("href");
var n = i.replace("http://www.pantsumation.com", "https://www.pantsumation.com");
$(this).attr("href", function() {
return n;
})})});
UPDATE
Reading what you're actually trying to do rather than the question you asked, you might find it easier to simply replace the protocol wherever it's found:
$("a[href]").each(function(){
if( this.protocol === "http:")
this.protocol = "https:"
});
That selector ensures you're only getting links with href's in them. You can make a more refined selector if you don't want to get external links or similar.

Two URL's in function using "window.location.href"

I'm using a Marketo Embed for which allows me to add to it when I use it.
My goal is to use the "window.location.href" function to open the first URL (a .zip file) and then open a new URL (a page).
It's only using one of the URLS. Either one will work properly if they are the only one if the function. Otherwise it only fires the latter one. I've tested it and it all appears to be right, but it think I'm missing something about the rules with using window.location.href twice.
Here is my code:
<script src="//app-sj01.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_1198"></form>
<script>MktoForms2.loadForm("//marketo.com", "000-000-000", 0000, function(form) {
form.onSuccess(function(values, followUpUrl) {
window.location.href = "************.zip";
window.location.href = ".../page.html";
return false;
});});
</script>
try
<script src="//app-sj01.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_1198"></form>
<script>
MktoForms2.loadForm("//marketo.com", "000-000-000", 0000, function(form) {
form.onSuccess(function(values, followUpUrl) {
var pid = window.setInterval(function() {
window.location.href = ".../page.html";
typeof pid !== 'undefined' && window.clearInterval(pid);
}, 1000);
window.location.href = "************.zip";
return false
;});
});
</script>

How to check in # in url?

Sometimes because of cache I add # in my url, like this:
http://www.example.com/#lang=3201954253
What I need is to check if there is #lang in url and remove it if present.
you can clear the hash.
window.location.hash = '';
or you can even use history api History Api. history.pushState and replaceState
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one.
window.history.replaceState( {} , 'foo', '/foo' );
You may try like this:
if(window.location.hash) {
// code
} else {
// code
}
or you may try this:
<script type="text/javascript">
if (location.href.indexOf("#") != -1) {
//code
}
</script>
If you want to remove it then you may try this:
window.location.hash = ''
On a side note:
You may try
window.location.href.split('#')[0]
to remove anything after # without refreshing your page.
if (window.location.hash.indexOf("lang")) {
window.location.hash = "";
}
var tel = window.location.href;
if(tel.indexOf("#") > -1){
alert("found");
} else {
alert('not found')
}

Reload JavaScript files without refreshing HTML

I've a HTML which loads several Javascript files:
<script src="assets/js/a.js"></script>
<script src="assets/js/b.js"></script>
<script src="assets/js/jquery.min.js"></script>
As I debug/test my Javascripts in my browser's console, is it possible to reload these Javascript files without the need to reload the entire HTML page?
You could remove and then re-add them:
$('script').each(function() {
if ($(this).attr('src') !== 'assets/js/jquery.min.js') {
var old_src = $(this).attr('src');
$(this).attr('src', '');
setTimeout(function(){ $(this).attr('src', old_src + '?'+new Date()); }, 250);
}
});
Nope (at least not without a hack), in fact - be very careful reloading so much. It's quite possible that your javascripts become cached, which leads to many-a-headache trying to debug, since your updates are not applying.
https://superuser.com/questions/36106/force-refreshing-only-javascript-files-in-firefox-and-chrome
Based on PitaJ's solution.
Reload all javascript in a function. You can call this from anywhere you want.
$('script').each(function () {
if ($(this).attr('src') != undefined && $(this).attr('src').lastIndexOf('jquery') == -1) {
var old_src = $(this).attr('src');
var that = $(this);
$(this).attr('src', '');
setTimeout(function () {
that.attr('src', old_src + '?' + new Date().getTime());
}, 250);
}
});
Tested with jQuery 2.0.3 and chrome 43
function reloadScript(id) {
var $el = $('#' + id);
$('#' + id).replaceWith('<script id="' + id + '" src="' + $el.prop('src') + '"><\/script>');
}
Chrome is complaining, but works:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
Your script tag has to have id.
Call in console:
reloadScript('yourid');
Does not remove event listeners, so for for example button click gets executed twice if once reloaded.

Categories