On my website i have many outside links, as well as internal links.
i'd like some kind of solution in javascript or w/e that detects outside links and opens them in a new tab, but leaves internal links to be opened in the same tab.
thanks! =)
function getXterlinks()
{
var Xterlinks = document.getElementsByTagName('A');
for (var i=0;i<Xterlinks.length;i++)
{
var eachLink = Xterlinks[i];
var regexp_isYourdomain="your-domain.com";
var regexp_ishttp=/(http(.)*:\/\/)/;
if( (eachLink.href != null) && (eachLink.href.match(regexp_isYourdomain) == null) && eachLink.href.match(regexp_ishttp)!=null )
{
eachLink.target ="_blank";
}
}
}
Source: http://www.mediawiki.org/wiki/Manual:Opening_external_links_in_a_new_window#How_to_make_external_links_open_in_a_new_window
Yeah, well, jQuery's still JavaScript. How about:
$('a[href^="http://your-domain.com"]').attr("target", "_self");
$('a').not('a[href^="http://your-domain.com"]').attr("target", "_blank");
Not sure about the second, though, but you get the idea.
I wrote this solution for my personal web site. As long as you like jQuery (which you should, imho), you can include this in a common js file and forget about it. It will work with dynamic content, and will not force internal links to open in the current tab if you set target="_blank".
$(function() {
$('body').on('click', 'a', function() {
var currentHost = document.location.protocol+'//'+document.location.hostname;
if (this.href.indexOf(currentHost) != 0 && (this.href.indexOf('http') == 0 || this.href.indexOf('ftp') == 0)) {
window.open(this.href, '_blank');
return false;
}
});
});
Note: If you are using jQuery < 7, use .bind() instead of .on()
See it in action on http://www.seanknutson.com.
Related
I am looking for a way to set it up so that when an external link is clicked it will warn people that they are leaving the site. Preferably, it would darken the screen and display a message in the middle of the screen in a box with the option to click OK or Cancel.
I tried to use this code:
$("a.external").click(function () {
alert("You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.");
});
and give each link a class of external but it doesn't seem to work. I don't want to use this because it means that the client will have to remember to add the class I would prefer something more automatic.
I also tried to use this code to do so but to no avail:
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
var x=window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
var val = false;
if (x)
val = true;
else
val = false;
return val;
});
I am using WordPress 3.8.1.
Thanks in advance for any help you can give.
Your filter logic should be correct, Try using the confirm function, and using jQuery instead of $.
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are about to proceed to an external website."))
{
// if user clicks 'no' then dont proceed to link.
e.preventDefault();
};
});
I tried this out in dev tools on your site and it seems to work correctly if you use jQuery. I think you may have some plugin that is causing conflicts with $.
JSFiddle Demo
Try using confirm instead of alert since that will pause and wait for user input. You'll then need function(e){ e.preventDefault(); } to prevent the default link actions.
To identify just external links you might do something like this:
var ignoreClick = false;
$(document).ready( function(){
$('input[type="submit"], input[type="image"], input[type="button"], button').click(function(e) {
ignoreClick = true;
});
$(document).click(function(e) {
if($(e.target).is('a'))
checkLink(e);
});
$('a').click(function(e) {
checkLink(e);
return true;
});
checkLink = function(e){
// bubble click up to anchor tag
tempTarget = e.target;
while (!$(tempTarget).is('a') && !!tempTarget.parentElement) {
tempTarget = tempTarget.parentElement;
}
if ($(tempTarget).is('a')){
if(!!tempTarget && $(tempTarget).is('a') &&
(tempTarget.hostname == "" || tempTarget.hostname == "#" || tempTarget.hostname == location.hostname)){
ignoreClick = true;
}
}
}
});
and to catch people with a message you might use beforeunload and the confirm option
$(window).bind("beforeunload", function (e) {
if (!ignoreClick){
if(!confirm("Leaving website message")) {
e.preventDefault();
}
}
});
It worked pretty well to me. I just removed unnecesary variables, but original script worked fine.
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
return window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
});
http://jsfiddle.net/3dkAN/1/
EDIT
Following #user1308743's line, seems that in cgmp.framework.min.js is summoning the jQuery.noConflict() mode, that unbinds the $() function for jQuery. So please use jQuery() for any jQuery implementation
I'm using the HTML5 tag details for a FAQ section of a company. An issue was that if the user opened another question the other question would not close automatically. Therefore I searched on the web and found the following solution:
function thisindex(elm){
var nodes = elm.parentNode.childNodes, node;
var i = 0, count = i;
while( (node=nodes.item(i++)) && node!=elm )
if( node.nodeType==1 ) count++;
return count;
}
function closeAll(index){
var len = document.getElementsByTagName("details").length;
for(var i=0; i<len; i++){
if(i != index){
document.getElementsByTagName("details")[i].removeAttribute("open");
}
}
}
This code does work properly in some sense but it has some small issues. Sometimes it opens two questions at the same time and works funny. Is there a method so this can work properly? This should work on desktop, tablet and mobile.
NOT DESIRED EFFECT:
I created a fiddle http://jsfiddle.net/877tm/ with all the code. The javascript is doing it's work there, ig you want to see it live click here.
Since you tagged jQuery, you can just do this:
$('.info').on('click', 'details', function () {
$('details').removeAttr('open');
$(this).attr('open', '');
});
All this does is remove the open attribute of all detail tags when you click on any detail, and then reopen the one you just clicked on.
http://jsfiddle.net/877tm/3/
the hole thisindex function is stupid and can be removed. You can simply pass the details element to closeAll.
The closeAll is quite stupid, too it searches for details in the for loop, wow.
// closeAll
function closeAll (openDetails){
var details = document.getElementsByTagName("details");
var len = details.length;
for(var i=0; i<len; i++){
if(details[i] != openDetails){
details[i].removeAttribute("open");
}
}
}
In case you want write clean code.
You should use $.on or addEventlistener.
Try to be in a specific context and only manipulate details in this context. (What happens, if you want to have two accordion areas. Or some normal details on the same site, but not inside of the group.)
Only search for details in the group, if details was opened not closed.
Give the boolen open property some love, instead of using the content attribute
I made small fiddle, which trys to do this.
To make details as accordion tag you can use below jquery.
$("#edit-container details summary").click(function(e) {
var clicked = $(this).attr('aria-controls');
closeAll(clicked);
});
function closeAll (openDetailid){
$("#edit-container details" ).each(function( index ) {
var detailid = $(this).attr('id');
var detailobj = document.getElementById(detailid);
if (openDetailid != detailid ) {
detailobj.open = false;
}
});
$('html, body').stop().animate({ scrollTop: $('#'+openDetailid).offset().top -100 }, 1000);
}
I have a solution with jQuery
$('details').on('click', function(ev){ //on a '<details>' block click
ev.preventDefault(); //prevent the default behavior
var attr = $(this).attr('open');
if (typeof attr !== typeof undefined && attr !== false){ //if '<details>' block is open then close it
$(this).removeAttr('open');
}else{ // if '<details>' block is closed then open the one that you clicked and close all others
var $that = $(this); //save the clicked '<details>' block
$(this).attr('open','open'); //open the '<details>' block
$('details').each(function(){ //loop through all '<details>' blocks
if ($that.is($(this))){ //check if this is the one that you clicked on, if it is than open it or else close it
$(this).attr('open','open');
}else{
$(this).removeAttr("open");
}
});
}
});
I'm making a php/html app which show some data in a table, when the user clicks in the row (<tr>) jquery open that record.
This is the code:
$.fn.linkRow = function(element) {
thisRow = this.find('tbody tr');
thisRow.on('click', function() {
hrefLocation = $(this).find('td.link:first a').attr('href');
if (hrefLocation) {
window.location.href = hrefLocation;
};
}).addClass((thisRow.has('td.link')) ? 'pointer' : '');
return this;
};
The fact is: The user can't open a record in a new tab. The only way is copy&paste the href... And my users won't do that.
If make some research about the event fired by the scroll button and how to open a new tab, the later is almost impossible, so... Does anyone can figure a way?
EDIT: I mean the mouse-wheel... Normally this open a link in a new tab.
PS: I have to use tables, In some point I will make a css-based table layout for that (no javascript needed), but I can't do it in this version of the software.
Thanks!
This is the final code:
$.fn.linkRow = function(element) {
thisRow = this.find('tbody tr');
thisRow.not('a').on('mouseup', function(e) {
hrefLocation = $(this).find('td.link:first a:first').attr('href');
if ( hrefLocation ) {
if (e.which == 2) {
window.open(hrefLocation);
}
else{
window.location.href = hrefLocation;
}
};
}).addClass( ( thisRow.has('td.link') ) ? 'pointer' : '' );
return this;
};
BUT... The mouse-wheel click does not work for what I intend:
If you click a link (a tag) > open a new tab
If you click a no link (any other tag) > it will scroll based on your mouse position. if you move your mouse up, it scrolls up and so
So... I works but I definitively need to make a no-javascript solution.
If you want to have the links open in a new tab and not in the same page, you need to replace
window.location.href = hrefLocation;
with
window.open(hrefLocation);
Change click with mouseup and catch e.with with value 2 (middle button):
$.fn.linkRow = function(element) {
thisRow = this.find('tbody tr');
thisRow.on('mouseup', function(e) {
hrefLocation = $(this).find('td.link:first a').attr('href');
if ( hrefLocation ) {
if (e.which == 2) {
window.open(hrefLocation);
}
else{
window.location.href = hrefLocation;
}
};
}).addClass( ( thisRow.has('td.link') ) ? 'pointer' : '' );
return this;
};
Try with the following method
$(document).scroll(function(){
if(!tabOpen){
window.open('url', 'window name', 'window settings');
tabOpen = true;
}
});
I faced a similar problem a few months ago.
Either you wrap every td-content into a normal a-Tag (and use _target="blank"), no javascript required in this case!
...or you use js:
thisRow.click(function(){
window.open('url', 'window name', 'window settings');
return false;
});
window.open() will do the trick but it also depends on the browser configuration
Not sure what you mean with the scroll button, but if it's the mouse-wheel then you can use this script to fire events on wheel-up/-down.
http://brandonaaron.net/code/mousewheel/demos
I'm unsure if you want to know how to make an middle click event with jquery or if you want to know how to open a new tab but here goes:
Middle click event:
$("tr").live('mousedown', function(e) {
if( (e.which == 2) ) {
alert("middle button");
}
e.preventDefault();
});
New tab:
As all the others are saying, use the following:
window.open(href);
With both middle click and open link:
$("tr").live('mousedown', function(e) {
if( (e.which == 2) ) {
window.open(href);
}
e.preventDefault();
});
EDIT:
Some sources:
Jquery: detect if middle or right mouse button is clicked, if so, do this:
The answer to Detect middle button click (scroll button) with jQuery can also help solve some compatibility issues with IE
To open in a new tab use:
window.open(hrefLocation);
window.open(hrefLocation,'_blank'); //Or this
window.open(hrefLocation,'_newtab'); //Or this
One of these should work.
This is a known issue for iScroll and it only seems to happen in iOS5 where the menu completely stops working. All my sub links in iScroll are hash anchors. Does anyone have a workaround for this?
The way I handled it was to hijack the anchor links themselves and replace them with scrollToElement calls instead.
// Hijack hash anchors and scroll to them
$('a').click ( function (e) {
var id = $(this).attr('href');
if (id.substr(0,1) == '#') {
e.preventDefault();
setTimeout( function() {
scroller.scrollToElement ( id, 0 );
}, 0);
return false;
} else {
return true;
}
});
This code should only hijack links that begin with #. It then handles the scrollToElement in a setTimeout which fixes some other intermittent bugs. It works well on my end as long as your anchors are properly named with id's. If you are using name attributes instead of id attributes, you'll need to rewrite these.
This code will copy name attributes and put them in the id attribute if it is blank. You probably won't need this, though.
$('a').each (function (i, e) {
var n = $(e).attr('name');
var id = $(e).attr('id');
if ( typeof id == 'undefined' || id === null || id === '') {
$(e).attr('id', n);
}
});
I am having a problem with the hashchange event in Firefox. We are using the JQuery hashchange plugin provided by Ben Alman. The code is as follows.
$(window).hashchange(function (e) {
alert("Hello");
//we want to perform a post in here.
});
var temp = "#123";
if (temp !== "") {
if (window.location.hash == temp) {
$(window).hashchange();
}
else{
window.location.hash = temp;
}
}
else {
window.location.hash = "#Home/Home";
};
Now this works fine in IE9 and Chrome, however in Firefox, I see the alert, but as soon as I click OK, the page refreshes, displays the alert again, and continues infinitely. Is there some sort of weird behaviour that Firefox uses that I am unaware of? Or is there simply some other problem that is hidden deeper?
In some browsers window.location.hash includes the # and in some don't so its better if your ignore it while comparing the hash value in your code.
Try this.
$(window).hashchange(function (e) {
alert("Hello");
//we want to perform a post in here.
});
//Remove hash from here which will be compared with window.location.hash
var temp = "123";
if (temp !== "") {
//Replace # by empty nothing
if (window.location.hash.replace('#', '') == temp) {
$(window).hashchange();
}
else{
window.location.hash = '#' + temp;//Now add the hash here
}
}
else {
window.location.hash = "#Home/Home";
};
We located the problem as occuring in MicrosoftAjax.js and found the following solution:
Firefox 6 Infinite Page Refresh With Page With Hash Tags