Adding rest of URL before shortened links - javascript

I'm creating a Chrome extension for a browser game and one of the features I'd like to add is a floating "latest posts from the forum" window to the right of the game. I've gotten it displaying the way I want it to but, all of the links pulled from the forum are shortened and don't include the full URL. When I click on one of the links it tries to go to that page on the games site rather than the forum site. What I'd like is for my code to fix the URL as well as add a target blank attribute so the links open in a new page/tab. My existing code is below.
$(function(){
var hzsforumpostsss = document.getElementById('latestpostsHZ');
hzsforumpostsss.insertAdjacentHTML('afterend', '<div><div id=\"hzlatestforumss\" style=\"background-color: rgba(0, 110, 187, 0.9);position:absolute;left:50%;width:280px;margin-left:390px;font-size:9pt;display:block;overflow:auto;\"></div></div>');
$('#hzlatestforumss').load('https://cors-anywhere.herokuapp.com/http://heroes-rising-forum.2349640.n4.nabble.com/');
})

Since you're just loading the content directly into your div with some AJAX, you're going to need to loop through all the links in the div and prepend the hostname to the ones which are relative. Your mix of jQuery and vanilla JS is a little confusing, but I'll just stick to vanilla JS for my example code.
[...document.getElementById('hzlatestforumss').getElementsByTagName('a')].forEach(anchor => {
if (anchor.href && !anchor.href.includes('://')) {
if (!anchor.href.startsWith('/')) { anchor.href = '/' + anchor.href; }
anchor.href = 'http://heroes-rising-forum.2349640.n4.nabble.com' + anchor.href;
}
});
You can also add the _blank target in the same loop if you want.

THANK YOU for getting me on the right track! The code I ended up with is below.
$(function(){
var hzsforumpostsss = document.getElementById('latestpostsHZ');
hzsforumpostsss.insertAdjacentHTML('afterend', '<div><div id=\"hzlatestforumss\"'+
'style=\"background-color: rgba(0, 110, 187, 0.9);position:absolute;left:50%;width:280px;margin-left:390px;display:block;overflow:auto;\"></div></div>');
$('#hzlatestforumss').load('https://cors-anywhere.herokuapp.com/http://heroes-rising-forum.2349640.n4.nabble.com/');
setTimeout(function(){
$('a[href*="/"]').each(function(){
var current = $(this).attr("href");
$(this).attr("href", "http://heroes-rising-forum.2349640.n4.nabble.com" + current);
$(this).attr("target", "_blank");
});
},2000);
})

Something like this?
$(function(){
var hzsforumpostsss = document.getElementById('latestpostsHZ');
hzsforumpostsss.insertAdjacentHTML('afterend', '<div class="HideFJcontainer" style=\"position:absolute;left:50%;width:280px;margin-left:390px;display:block;overflow:auto;\">'+
'<input type="checkbox" class="HideFJforum"> Hide/Show Forum<div id=\"hzlatestforumss\"></div></div>');
$('#hzlatestforumss').load('https://cors-anywhere.herokuapp.com/http://heroes-rising-forum.2349640.n4.nabble.com/',
function(){
$('a[href*="/"]').each(function(){
var current = $(this).attr("href");
$(this).attr("href", "http://heroes-rising-forum.2349640.n4.nabble.com" + current);
$(this).attr("target", "_blank");
});
} );

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.

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/

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.

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