&-sign is ruining my link-rewriter - javascript

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);

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.

Display Image Based on URL Ending (Variable or Attribute) [Pound/Number Sign # ]

I need an image to be displayed based on the ending of a URL.
For example, I need "123.jpg" to be displayed when someone visits:
website.com/view/#123
website.com/view/#123.jpg
website.com/view#123
website.com/view#123.jpg
(whichever is recommended or would actually work)
I'm looking for the end result to be: < img src=123.jpg" >
Thanks in advance. I will sincerely appreciate any assistance.
(By way of background or additional information, I need this for Facebook's sharer.php so that people can share one of hundreds of images on a given webpage (for example, website.com/blog and they happen to love the 123rd image on there), they click the link to share that specific image (123.jpg), and then any of their friends who clicks on the link (website.com/view/#123) will arrive at a themed page with just the image in the middle (123.jpg) and nothing else, and then they can click around the rest of the website. The main benefit is that 123.jpg will be the only image that shows up as a thumbnail on the Facebook Feed or "Wall".)
window.onhashchange = function() {
if (location.hash) {
var url = location.hash.substr(1); // strip the # char
if (url.indexOf('.') == -1) {
url += '.jpg';
}
document.getElementById('myImg').src = url; // show the image; value of the variable 'url'
}
};
window.onhashchange(); // call the event on load
Use something like this.
$(document).ready(function(){
var url = document.URL; //get the url
if ( url.indexOf("#") != -1 ) //check if '#' is present in the url
{
var split_array = url.split("#");
var image_url = split_array[split_array.length - 1];
//display the image
}
});
Try this out,
$(document).ready(function() {
getImageSrc();
$(window).on('hashchange', getImageSrc); // will always lookout for changes in # URL
});
function getImageSrc() {
if(window.location.hash) {
var imgSrc = window.location.hash.substr(1);
if(imgSrc.indexOf('.') == -1 ) {
imgSrc = imgSrc + ".jpg";
}
alert(imgSrc);
}
}

Identify links with relative path in jQuery

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/

This script applies specific attr to all links on the website. How to exclude pdf and zip files?

I'm building Wordpress website where all pages are being loaded using Ajax. I'm using script created by Chris Coyer that can be found here. Code below will add specific tags to all links on the website. Wordpress will try to load content from those links using Ajax. Problem is that those attributes are being applied on links to PDF and ZIP files which are meant to be downloaded, not loaded into page.
How I can exclude specific file formats from getting those attributes? I already tried something like this $internalLinks = $("a[href^='"+siteURL+"']:not([href$=/*.pdf])") but that didn't work for me. Am I doing something wrong?
Below is part of the original code that adds attributes. Full code can be found on this JSFiddle page. Thanks!
var $mainContent = $("#main-content"),
siteURL = "http://" + top.location.host.toString(),
$el = $("a");
function hashizeLinks() {
$("a[href^='" + siteURL + "']").each(function() {
$el = $(this);
// Hack for IE, which seemed to apply the hash tag to the link weird
if ($.browser.msie) {
$el.attr("href", "#/" + this.pathname).attr("rel", "internal");
} else {
$el.attr("href", "#" + this.pathname).attr("rel", "internal");
}
});
};​
You can't use * as a wildcard like a filespec. Just use this:
$internalLinks = $("a[href^='"+siteURL+"'):not([href$='.pdf'])");
You can apply a filter on all matched links:
var $mainContent = $("#main-content"),
siteURL = "http://" + top.location.host.toString(),
$el = $("a");
function hashizeLinks() {
$("a[href^='" + siteURL + "']").filter(function(){
return this.href.match(/[^\.pdf]$/i);
}).each(function() {
$el = $(this);
// Hack for IE, which seemed to apply the hash tag to the link weird
if ($.browser.msie) {
$el.attr("href", "#/" + this.pathname).attr("rel", "internal");
} else {
$el.attr("href", "#" + this.pathname).attr("rel", "internal");
}
});
};​

Code isn't compatible with IE?

$(document).ready(function() {
var url = document.location.toString();
$('.tab').click(function() {
if($(this).is(".active")) {
return;
}
var classy = $(this).attr("class").split(" ").splice(-1);
var innerhtml = $('.content.'+classy).text();
$('#holder').html(innerhtml);
$('.tab').removeClass('active');
$(this).addClass('active');
});
var url = document.location.toString();
if(url.match(/#([a-z])/)) {
//There is a hash, followed by letters in it, therefore the user is targetting a page.
var split = url.split("#").splice(-1);
$('.tab.'+split).click();
}
else {
$('.tab:first').click();
}
});
Hey, I was just informed by one of my commenters that this code doesn't work in IE. I can't for the life of me figure out why. Whenever you switch tabs, the content of the tab doesn't change. Meanwhile the content of the #holder div is all the tabs combined.
Any ideas?
Not the answer you're after, but I'd seriously recommend looking into the jQueryui tabs widget if you can. It's made my life a lot easier dealing with this stuff at least.
Hard to tell without an IE version and a page to look at what exactly is happening- but here are some best guesses:
change:
if($(this).is(".active")) {
to:
if($(this).hasClass("active")) {
change:
var innerhtml = $('.content.'+classy).text();
to:
var innerhtml = $('.content .'+classy).text(); // note the space
change:
var url = document.location.toString();
to:
var url = document.location.hash;
I did all changes which Ryan suggested except adding the space between '.content' and the period as it is needed. He could not have known without the source code.
I changed your .splice(-1) to [1] so that I'm choosing the second item in the array, which is the class name. It looks like .splice(-1) is behaving differently in IE and other browsers.
I have tested the code with IE 7-8 and it works.
Source code as it is now:
$(document).ready(function() {
var url = document.location.hash;
$('.tab').click(function() {
if ($(this).hasClass("active")) {
return;
}
var classy = $(this).attr("class").split(" ")[1];
var innerhtml = $('.content.' + classy).text();
$('#holder').html(innerhtml).slideDown("slow");
$('.tab').removeClass('active');
$(this).addClass('active');
});
if (url.match(/#([a-z])/)) {
//There is a hash, followed by letters in it, therefore the user is targetting a page.
var split = url.split("#")[1];
$('.tab.' + split).click();
}
else {
$('.tab:first').click();
}
});

Categories

Resources