/    Sign up×
Community /Pin to ProfileBookmark

js for hyperlinks on a web page

I am looking for a js script that will monitor when a hyperlink is clicked and force that link into a new window or native application.

If the link is to a different web page, the link should open in a new window.
If the link is a word document, the document should open in word or the default editor.
If the link is within the same page, such as a back to top or bookmark, the link should stay on the page and simply go to the desired location.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@WebnerdJan 30.2010 — You can't "force" an application unless you set some headers from the server-side. The browser will do what it "thinks" it needs to do based on user settings and Javascript can't change this behavior.

However, you can add some code to check for links that start with "http://" and have them open in a new window:

<i>
</i>jQuery(function(){
$('a').each(function(){
if($(this).attr('href').match(/^http/i))
{
$(this).click(function(){ window.open(this.href','newWin','width=980,height=650');return false});
}
});
});


or just

<i>
</i>
window.onload = function()
{
var coll = document.getElementsByTagName('a');
for(i=0;i&lt;coll.length;i++)
{
if(this.getAttribute('href').match(/^http/i))
{
coll[i].onclick = function(){ window.open(this.href,'newWin','width=980,height=650');return false}
} <br/>
}
}

Copy linkTweet thisAlerts:
@goofy78270authorFeb 01.2010 — Forgive me for my inexperience, but I would simply add this within a script block at the top of the page correct? In addition, would there be a way to prevent links within the same page, such as a back to top, from opening in a new window?
Copy linkTweet thisAlerts:
@WebnerdFeb 02.2010 — Yes, add into a script block. The links should only open in new windows if they literally contain "http://" at the beginning. So, this script assumes your local links are all relative.
×

Success!

Help @goofy78270 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...