Identify links with relative path in jQuery - javascript

I wrote the below code to identify external links and then add "external" class to them. I implemented this on my site, it's working fine but there is one problem it is not working correctly for "Tabs" and "Reply to comment" options. There it's adding "external" class to them but they are local links. Let me know if there's something wrong with my code.
Link for tab is like this: Popular
and link for reply is like this: <a class="comment-reply-link external" href="/samsung-galaxy-ace-plus-s7500-how-to-root-and-install-custom-recovery-image/?replytocom=1044#respond" onclick="return addComment.moveForm("comment-1044", "1044", "respond", "420")">Reply</a>
I know that it's failing because these are not absolute links so location.host will not work for these links. Can you let me know how can I incorporate these links and add "local" class to them?
jQuery(document).ready(function ($) {
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});

Instead of getting the attribute, get the property:
var url = $(this).prop('href');
Or:
var url = this.href;
The difference is important:
> $('foo').prop('href')
"http://stackoverflow.com/questions/17130384/identify-links-with-relative-path-in-jquery#bar"
> $('foo').attr('href')
"#bar"
Also, I would use location.origin instead of location.host:
$('a').filter(function() {
return this.href.indexOf(location.origin) === 0;
}).addClass('local');
Demo: http://jsfiddle.net/q6P4W/

Related

How to get anchor text in a Session variable?

I am working on a project in which i have linked many pdf files in the master page.On clicking the anchor the page redirected to the specified page and displays pdf in iframe.Now i want the text in anchor tag to be displayed on the page where pdf is opened.
Consider I have an anchor which looks like this :
News Letter
Now i want the text " News letter" to be shown on the redirected page.
I think i could this by saving the text in session variable.But How can I save the anchor text in Session variable without specifying any id or class to the anchor tag? Can anyone help me please ?
You probably looking for QueryString instead of session, You are already passing path in QueryString, also pass the anchor text. You need to add this to url while you are creating the anchor tag.
News Letter
On server side
lblForAnchor.Text = Request.QueryString["aText"].ToString();
Edit you can not change the query string when it is created then you can change it when it is loaded in DOM in document.ready. Assign a class to your anchors to be specific.
$( 'a.someclass' ).attr( 'href', function(index, value) {
return value + '&aText=' + $(this).text();
});
Other way to do this on click of anchor.
$( 'a.someclass' ),click(function(event) {
window.location.href = this.href + '&aText=' + $(this).text();
});
You can try this
$("a").click(function (e) {
if($(this).attr("href").match(".pdf$"))
{
window.location.href = $(this).attr("href") + "&title=" + $(this).text();
e.preventDefault();
}
});
On server side in "Main_Content.aspx"
strTitle = Request.QueryString["title"];
You could Write the content dynamically with javascript:
News Letter
Javascript:
<script language="javascript">
function openWin(t,u) {
docstring='<iframe src='+u+'></iframe>';
win = window.open();
newdoc=win.document;
newdoc.writeln(t);
newdoc.write(docstring);
newdoc.close();
}
var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
var theAnchor = elements[i].innerHTML;
var theHref = elements[i].href;
if(theHref.match(/\.pdf/)){
openWin(theAnchor,theHref);
}
}
</script>
Or call a different address with URL and test as parameters and generate the doc on the server side.
I'm not sure how this will behave with the link click but it might be worth a shot.
links should not have to be modified.

have only one class name append to the end of href of an anchor tag?

var myClass;
jQuery(".option-set a").click(function() {
myClass = jQuery(this).attr("class");
jQuery("a.perma").each(function() {
var _href = jQuery(this).attr("href");
jQuery(this).attr("href", _href + "#filter=." + myClass);
});
});
Im using this code to append the class name of the filters to the end of the permalink for each thumbnail here
The issue Im running into now is that the class keeps getting assigned to the end of the permalink with each click so if I click on print then web then photography the url of the permalink would appear as: /#filter=.print#filter=.web#filter=.photography which still works, however it would be great if for the sake of tidiness it only displayed the last one.
Also once a thumbnail is clicked and the next page is loaded, I need the thumbnails to maintain the current permalink of the filter selected. Any ideas would be appreciated. I just cant seem to figure this out. I truly appreciate the help!!
call it just once not on every click...
jQuery(document).ready(function() {
myClass = jQuery('.option-set a').attr("class");
jQuery("a.perma").each(function() {
var _href = jQuery(this).attr("href");
jQuery(this).attr("href", _href + "#filter=." + myClass);
});
jQuery(".option-set a").click(function() {...});
});
This modification should check if current class filter is not present.
jQuery("a.perma").each(function() {
var _href = jQuery(this).attr("href"),
newHref = _href.indexOf(myClass) === -1 ? _href + "#filter=." + myClass : _href;
jQuery(this).attr("href", newHref);
});
});
And to maintain filtered thumbnail urls on next page load you need to work with server and parse what parameters it passes or use Web storage to save current filtered path and set thumbnail hrefs accordingly on document load.

Is there a way to open all <a href> links on a page in new windows?

I have a bunch of <a href=".html"> links and want to make them all open in new windows.
I know I can do a search and replace all to add target="_blank" to all my <a href="..."> links.
However, is there a quick way, such as setting a CSS style, or adding some JavaScript code, to accomplish the same thing?
If you have a page consisting of only links, consider <base target="_blank">. This opens every link in a new window (but also includes the targets of forms, unless overridden with <form target="_self">.
As others have shown, without modifying the HTML source, you can use Javascript to iterate through all <a> tags and add the target attribute or add an event listener that sets the target attribute dynamically.
If you have jQuery it's simple
$("a").attr("target", "_blank");
Or regular Javascript
var links = document.links;
for (var i = 0; i < links.length; i++) {
links[i].target = "_blank";
}
As per #Lekensteyn's suggestion, without Javascript (added for Completeness)
<base target="_blank">.
CSS: No.
JavaScript: Delegate a click event, which adds a target="_blank" attribute on click of a link.
document.body.addEventListener(function(e) {
if (e.target.nodeName.toUpperCase() === 'A' && e.target.href) {
e.target.target = '_blank';
}
}, true);
Note: If the <a> element contains other elements, you might want to traverse the tree to find out whether an anchor element is clicked:
document.body.addEventListener(function(e) {
var target = e.target;
do {
if (target.nodeName.toUpperCase() === 'A' && target.href) {
target.target = '_blank';
break;
}
} while (target = target.parentElement);
}, true);
Or, if you're a jQuery-lover:
$('body').on('click', 'a', function(e) {
e.target.target = '_blank';
});
yep, u can add attribute with JS to all links in HTML document named 'target' with value '_blank' ;)
You could also open replace href's of all links from url to javascript:openInWindow(url) using this, and writing function in JS that opens new window and set's it's location to url ;) Google will help you with both.
Just add a html base element to the page using Javascript:
var e = document.createElement("base");
e.target = "_blank";
document.head.appendChild(e);
I've used pure vanilla JavaScript to create a script that makes all the links open in a new window.
<script type="text/javascript">
var all_links = document.querySelectorAll("a");
for (let index in all_links) {
try {
all_links[index].setAttribute("target", "_blank");
}
catch (error) {
//console.log(error);
}
}
</script>

&-sign is ruining my link-rewriter

I'm currently writing a userscript that runs on another site. One function is to rewrite the links so you skip one landing page. However, if the &-sign exists in the link, my function will output it as & instead of &.
$('a').each(function(index) {
var aLink = $(this).attr('href');
if(aLink) {
if(aLink.indexOf("leave.php?u=") > 0) {
aLink = aLink.substring(38);
$(this).attr('href', decodeURIComponent(aLink));
}
}
});
This is one example of a link that gets ruined:
https://www.site.com/exit.php?u=http%3A%2F%2Fsverigesradio.se%2Fsida%2Fartikel.aspx%3Fprogramid%3D104%26amp%3Bartikel%3D3406950
Is a link to:
http://sverigesradio.se/sida/artikel.aspx?programid=104&artikel=3406950
But becomes this instead:
http://sverigesradio.se/sida/artikel.aspx?programid=104&artikel=3406950
The & entity is built right into that URL, so there's nothing for it except to just replace it.
Use:
aLink = aLink.substring (38);
aLink = decodeURIComponent (aLink);
aLink = aLink.replace (/&/gi, "&");
$(this).attr ('href', aLink);

Javascript to redirect from #anchor to a separate page

I have a set of links with #anchors pointing to a single webpage and I would like to smoothly move to a model with a separate webpage for each of those links. I want the old links to keep working using a redirect.
Old link style:
/all_products#A
/all_products#B
/all_products#C
New link style:
/products/A
/products/B
/products/C
I know that the server does not receive the #anchor name in the request but Javascript might.
Is it possible to automatically redirect from /all_products#A to /products/A using Javascript?
JQuery would be fine, it's being used on the site anyway.
I added this new answer to include some best practices for both extracting the hash from the url and doing a redirect.
// Closure-wrapped for security.
(function () {
var anchorMap = {
"A": "/products/A",
"B": "/products/B",
"C": "/products/C"
}
/*
* Best practice for extracting hashes:
* https://stackoverflow.com/a/10076097/151365
*/
var hash = window.location.hash.substring(1);
if (hash) {
/*
* Best practice for javascript redirects:
* https://stackoverflow.com/a/506004/151365
*/
window.location.replace(anchorMap[hash]);
}
})();
Put this as close to the top of your HTML <head> as you can so that it can execute before the rest of the page resources download:
<script>
function checkURL() {
var old_path = '/all_products';
if (window.location.pathname != old_path) {
// Not on an old-style URL
return false;
}
// Some browsers include the hash character in the anchor, strip it out
var product = window.location.hash.replace(/^#(.*)/, '$1');
// Redirect to the new-style URL
var new_path = '/products';
window.location = new_path + '/' + product;
}
checkURL();
</script>
This will check the current page URL and redirect if it matches the old-style path.
This code makes use of the window.location object which contains all the parts of the current URL already split up into component parts.
Making this script more generic is left as an exercise for the implementer.
I hope this can help :)
var urlSplit = document.URL.split("#");
if (urlSplit[1]) {
location.href = "http://www.example.org" + "/" + urlSplit[1];
}
else {
location.href = "http://www.example.org";
}
With jquery, either just replace the href with the correct one:
$('a').each(function() {
this.href = this.href.replace(/all_products#/, 'products/');
});
or capture clicks and redirect:
$('a').click(function() {
window.location = this.href.replace(/all_products#/, 'products/');
return false;
});
this might help:
A
B
C
D
E
<script type="text/javascript">
function redirectMe(a){
var aa=a+"";
window.location=aa.replace(/#/g,"/");
}
</script>

Categories

Resources