Prefixing a URL in an window.open function jQuery - javascript

I have this HTML:
Track Your Package »
Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:
$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});
However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...
The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.
I hope I've been clear and you can help me. Thanks.

You can use .each() to iterate over each matching element and change them individually:
$('a[onclick^="window.open(\'TrackPackage.asp"]').each(function(index, element) {
element = $(element);
element.attr('onclick', element.attr('onclick').replace(/open\('/, 'open(\'http://www.example.com/'));
});​
However, I don't think using links with a href of # and an onclick opening a window is as semantic as it could be. If possible, try changing the markup to this:
Track Your Package »
Now if someone is curious where it will lead them, the browser can show something useful in the status bar when you hover over it.
If you need to adjust the behavior further, add a class and bind for the click event. When they click, prevent the default action and open the window yourself, as you did before.

Why are you doing the click even inline like that? I would just output the links like:
Link Text
And then:
$('a[target=_blank]').click(function(){
var prefix = 'http://domain.com';
window.open(prefix + $(this).attr('href'));
});

Related

Change all external links using jQuery

I want to change all external links on my blog (blogspot here, that's why I'm looking for jQuery code) without changing the posting of my blog because I need a lot of work if I do that.
For example, my website is example.com.
I want to change all external links to
http://example.com/p/go.html?url=http://externallink.com
without need for any changes on my blog post. I don't have any idea to start with.
SOLVED: https://gist.github.com/2342509 Thanks everyone :D I just need to change it a bit.
In jQuery you can try:
// DOM ready
$(function(){
$('a[target="_blank"]').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');
});
Ofcourse this will only work if you have set the target="_blank" property/attribute in HTML and if you want all links to open the same url. This idea derives from the fact you want to have external links open automatically in a different tab/window.
If this is not the required functionality, you can use a custom data- attribute in a similar way. Only difference is you will need to loop each link, and get the data from it.
// DOM ready
$(function(){
$('a[data-href]').each(function(){
var anc = $(this),
href = anc.prop('href'),
dataHref = anc.data('href');
anc.prop('href', href + '?url=' + dataHref);
});
});
HTML example:
external link
And now you will probably need to add more information if that is still not what you want.
Going off of #Tim Vermaelan's answer, you could try this, which will check for every link that doesn't start with your website's URL without relying on it being target="_blank":
$('a:not([href^="http://yoursite.com"])').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');

Removing data attributes from HTML using jQuery

Can't seem to get this one to work...
I have a page that hides certain links. When the DOM is loaded, I'm using jQuery to toggle some of those elements. This is driven by using a data attribute like so:
<div class="d_btn" data-usr='48'>
<div class="hidden_button">
Then, I have the code:
$.each($(".d_btn"), function() {
var btn = $(this).data('usr');
if ( btn == '48' ){
$(this).children('.hidden_button').toggle();
}
The above all works as planned. The problem is that I am trying to remove the data-usr from the class .d_btn once the if statement is evaluated. I've tried the following and nothing works (i.e., after the page is loaded, the source still shows the data-usr attribute:
$(this).removeAttr("data-usr");
$(this).removeData("usr");
I've been working on this for a couple of hours now and...nothing! Help is greatly appreciated!
UPDATE
I've tried the great suggestions of setting the data attribute to an empty string but I'm still not getting the desired result.
To explain a little further, The reason I'm trying to remove the attribute is so when an ajax response adds another item to the page, the previously added items would already have the button either shown or hidden. Upon AJAX response, I'm calling the same function once the DOM is loaded.
Currently, when something is added via AJAX, it toggles all the buttons (showing the ones that were hidden and vice versa.) Ugh...
I'm also fully willing to try alternatives to my approach. Thanks!
UPDATE
Well, the light bulb just flashed and I am able to do what I want to do by just using .show() instead of .toggle()
Anyway, I'd still like to find an answer to this question because the page will be potentially checking hundreds of items whenever something is added - this seems horribly inefficient (even for a computer, hahaha.)
Why don't you set the value to a random value or empty variable instead if removeAttr does not work..
$(this).attr("data-usr" , '');
$(this).prop("data-usr" , '');
Changing the DOM doesn't affect the source. It affects the DOM, which you can view with the Inspector/Developer Tools. Right click => View Source will give you the original source of the page, not the actual current source as modified by JavaScript.
Set it to a blank string:
$(this).attr("data-usr", "");
I second what Kolink said: check the DOM, not the source. (Chrome: Ctrl + Shift + i).
As others have stated. Checking the source will only show the original unedited source for the webpage. What you need to do is check the DOM using developer tools.
I've just checked everything in Chrome's inspector on jsfiddle here and the attribute is definitely being removed as well as the data.

How can I make a "reverse preventDefault" in jQuery?

In Private Logistics: Privacy-Sensitive Calendar, Todo, and Personal Information Management, data that is entered can be edited with a click, and there is support for either entering a link as <a href="... or entering a URL, which will be linkified.
This works great but it presents a problem when someone clicks on a link. The desired behavior is for the link to open and not to put the snippet of text into edit mode, which is the reverse of the usual pattern implemented by event.preventDefault()' or '...return false;}. (Clicks outside the link on the element should put the containing element in edit mode, same as a container that doesn't happen to have a link.)
How can I reverse the more common pattern using jQuery? My best guess now is to attempt introspection on the event target and see if it is an anchor. But that's just a best guess; I have seen plenty of examples of the pattern that would cancel the link loading another page but performing the added Ajax functionality of putting the container into edit mode; I'm not sure I've seen the reverse of that pattern which would follow the link and not put the container into edit mode.
I also see a way to dodge the matter by having links load in the same page, but that's the sort of solution I'd prefer to only adopt if there are intractable issues with implementation or the like.
Generally, you don't want to clean up your broad strokes, instead, don't make such broad strokes. Use an if statement prior to running e.preventDefault().
Something like:
var preventedLinks = $('a.preventthislink');
$('a').click(function(e){
if ($(this).index(preventedLinks) != -1) {
e.preventDefault();
}
});
you could alternatively just change the class of whatever you are preventing default on:
$(document).ready(function(){
$('.blue').removeClass('blue').addClass('green');
});

Change URL shown in Chrome status bar

When I hover over a url in Chrome, the url is displayed in the Chrome status bar. In my case this results in an ugly javascript:bla-bla-bla reference. Is there any way to change the contents of the status bar when you hover over a link?
Thanks
Although you selected your answer, this idea is an alternative.
You can change the href attribute on mouseover to affect what the status bar says, and change it back on mouseout or click:
function showNiceLink(el, e) {
e = e || event;
el.originalHref = el.originalHref || el.href;
console.log(e.type);
if (/click|out/i.test(e.type)){
el.href = el.originalHref;
} else {
el.href = "http://Linking...";
}
}
<a href="#this is a really UGLY link #1##$$%!!&"
onmouseover="showNiceLink(this,event)"
onmouseout="showNiceLink(this,event)"
onclick="showNiceLink(this,event)">a link with an ugly <code>href</code></a>
I'm pretty sure for security reasons this isn't possible in any browser. Otherwise links to phishing sites will become much, much harder to detect, because attackers can then just place a genuine URL in the status bar while the dangerous link actually leads elsewhere...
Use an onclick event handler for your hyperlink instead, and put a real, meaningful URL in the href attribute in place of the javascript: link (even if the link is meant to be used only with JavaScript).
Your "link"
I guess you mean you want to change what destination is shown for link that is selected? In that case you most likely should put nice url in href attribute, and use onclick attribute for your javascript. Not sure that you can duplicate everything what is done by putting javascritp in href.
Assuming this is what you have:
<a onClick="blabla">Link</a>
Add href="#" to it. Then the # should be shown in stead of the javascript:blabla.
So that would be like this:
Link
It is definitely possible to achieve the desired effect. Just look at what Google puts in the status bar of its search results.
However, you need to use some kind of a trick, e.g. onclick like BoltClock suggested.
Google shows you what you would like to see - a plain, clean URL.
Underneath, however, they use a long redirect URL with monitoring parameters to track you down as you click any result link. That way Google monitors which of the search results are clicked on and which are not.
Unfortunately, most people do not realize that. Quite frankly, I would be very glad to see a browser extension which takes all this dirty tricks down and replaces "tracking" URLs with the "real ones".

Making a span/div/p href-like or stopping href "executing" links

I have the problem to "stop" href executing any links.
So my question is:
1) Is it possible replace href-elements that generate internal (#) links with any component, maybe <p>, <div> or <span> (or whatever could be working) that keep the same behaviour of <a> element (hovering, underlined etc) but not executing any link?
2) Alternative, a "trick" to avoiding href elements execute links?
1 or 2 without using jquery or any other js library possibly
Thanks Randomize
There are all sorts of tricks that can be employed to do this kind of thing, but what you need to be careful of is modifying the behaviour from that which the users have come to expect from a browser.
For example , it would be possible to swap the meaning of 'OK' & 'Cancel' buttons, but this would just confuse the user. (An extreme example, I know, but you get the idea)
If you could supply some more information about why you are trying to do this, there may be a better way of approaching things.
You can either add an onclick attribute to specific <a> elements:
Or modify the href like this:
To make them look like links, without redirecting the browser.
If instead, you already have a bunch of links with hrefs, and you simply wish to make them all non-redirecting, then the following jQuery will do this to all links on the page:
$(function () {
$('a').click(false);
});
Although nice and short, the above only works with jQuery-1.4.3+. If you are using an older version, then you can use the expanded form:
$(function () {
$('a').click(function () { return false; });
});
Yes. You can prevent links from the default action - the recommended way is to have links work normally (in case JS is disabled or not available - think "mobile browsers"), and then override the default action with JS.
Unfortunately, due to cross-browser incompatibilities, there are three ways to do this ("traditional","W3C" and "IE") and you need all of them: stopPropagation(), cancelBubble and return false. See a complete example at QuirksMode: http://www.quirksmode.org/js/events_order.html#link9
(Incidentally most JS frameworks abstract this away, so in jQuery you'd do this:
$('a').click(function(event){
// do something on click here
event.preventDefault();
});
This does the same thing as the QuirksMode example, but is a easier-to-read example.)
TO disable the link via js add onclick="this.href='javascript:void(0)';" like so:
link text
You can use a similar tactic to make other elements work link links:
<div onclick="this.href='http://www.mysite.com';"></div>
This is working in IE, chrome and firefox:
text link
In the function return void(0):
function functionX() {
...
return void(0);
}

Categories

Resources