Transforming href links on pageload using jquery - javascript

I need to transform all the links(href values) to specific format
for example - if a page has a link http://www.exampledomain.com i want to convert its href to http://url.com/xyz?http://www.example.com
Below is the jquery i am using for this task (Note that i am new to jquery)
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
});
});
But above script is converting all the links of the website and my navigational links are also getting changed. How can we filter to change only the href's of links that contain 'http' and 'www'?
I know some kind of regex can be used for this purpose. Thanks in advance!

I thinks you should extract all internal links.
You can check if value match your criteria (http://www):
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.indexOf("http:\\www") > -1 ){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
But it will be better to extract all the internal links:
var myHost = new RegExp(location.host);
$('a').each(function(){
var value = $(this).attr('href');
if(!(myHost.test(value))){
$(this).attr('href','http://url.com/xyz?'+value);
}
});
The last and better option is to take just the external links: ( if you don't have to do anything to the internal)
$( document ).ready(function() {
$("a[href^='http']").each(function() {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});

You could try for the following code
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if(value.match("http://www.*"))
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});
You have to make sure that no navigation link contain
"http://www"
in them. Use relative links where you dont want to replace the href.
Or you could give a class to all anchor tags which you want to modify accordingly

Demo Fiddle
Check the anchor tag's href using element inspector
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
var value = $(this).attr('href');
$(this).attr('href','http://url.com/xyz?'+value);
}
});
using window.location.host and test
Modified from this article at CSS-Tricks.com

One approach:
// selects all 'a' elements:
$('a')
// sets the 'href' attribute, using the anonymous function to iterate over each
// 'a' element:
.attr('href', function(i,oldhref){
// i: the index of the current element in the returned collection,
// oldhref: the value of the 'href' before manipulation by the function.
// if 'exampledomain.com' features in the hostname of the link we
// manipulate the 'href' as required, otherwise we simply set the 'href'
// to its original value:
return this.hostname.indexOf('exampledomain.com') > -1 ? 'www.url.com/xyz?' + oldhref : oldhref;
});
JS Fiddle demo.
References:
JavaScript:
String.prototype.indexOf().
jQuery:
attr().

You can check the link is external or internal then you can add the additional effort.
$( document ).ready(function() {
$('a').each(function() {
var value = $(this).attr('href');
if($(this[href^='http'])
{
$(this).attr('href','http://url.com/xyz?'+value);
}
});
});

Related

Trim partial link in jQuery

I am trying to remove the start of a link in jQuery. I have tried to inject the following function but it doesn't work. What am I doing wrong?
JS
$(function() {
$('link-active').each(function() {
$(this).attr('href').remove('http://www.linkplus.com/xQWE=');
});
});
HTML
<td class="block">
<a class="link-active"
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>
When you're trying to search for classes, make use of dot (.), $('link-active') should be $('.link-active').
About .remove(): this one will remove one element of the DOM; not applicable in this case.
Solution: You will need to use .attr() to return AND update the href attribute of your tag, .replace() method should help.
$(function() {
$('.link-active').each(function() {
let href = $(this).attr('href'); //returns href value
let removableUrl = 'http://www.linkplus.com/xQWE=';
href = href.replace(removableUrl, ''); //replace the url you don't want with ''
$(this).attr('href', href); //update href value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="block">
<a class="link-active"
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>
Note: There's other methods to separate the url you don't want (if the url stay in the same format), check for:
.substring(): href = href.substring(removableUrl.length);
.split(): href = href.split('=')[1];
.replace() with regex: href = href.replace(/.*\=/,'');
Amend $('link-active') to $('.link-active').
First thing is While representing a class in jQuery try using dot notation..
$(function() {
$('.link-active').each(function() {
$(this).attr('href').remove('http://www.linkplus.com/xQWE=');
});
});
It's convenient to use attr method like this:
$(function() {
$('.link-active').attr('href', function(i, href) {
return href.replace('http://www.linkplus.com/xQWE=', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link-active" href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
Change your code on line 3 to
$(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));
Full code should be
$(function() {
$('link-active').each(function() {
$(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));
});
});
remove is not being used correctly here, as that method is meant to remove elements from the DOM and accepts a selector string as its argument.
Try something like this instead:
$(function() {
$('.link-active').each(function() {
var href = $(this).attr('href');
var strToReplace = 'http://www.linkplus.com/xQWE=';
$(this).attr('href', href.replace(strToReplace, ""));
});
});
Above we use replace to replace the start of the link with an empty string.
You have to get the string, replace it and then set it again.
Something like this:
$(function() {
$('link-active').each(function() {
replacement = 'http://www.linkplus.com/xQWE=';
url = $(this).attr('href');
$(this).attr('href', url.replace(replacement, ''));
});
});

jQuery doesn't let me use href

jquery:
$(".container").on("click", function(e) {
e.preventDefault();
var currentBox = $(this).siblings(".map").toggleClass("active");
$(".map.active").not(currentBox).removeClass("active");
});
html:
Because of this i cant use href anymore.
I use the jqueryto show more links.
It appears that you're trying to use div's and p's like anchors (a). href is not a valid attribute of div or p.
If you're trying to store data in the div and p tags, use data-href="" in conjunction with window.open()
Based on the limited code provided, my guess is that you're trying to do something like this:
$(".container").on("click", function(e) {
e.preventDefault();
const $this = $(this);
$(".map.active").removeClass("active");
$this.siblings(".map").toggleClass("active");
let href = $this.attr("data-href");
// Open a new window
window.open(href);
// OR
// Navigate without opening new window
window.location.href = href;
});
Or, you could skip the jQuery all together an just use anchor tags as they're designed to be used.
You can use jQuery for get any attribute of elements. So if you want to use href, just do:
var new_location = $('a').attr('href');
So you can do anything by click on a tag and at the least redirect to href path by:
window.location.href = $(this).attr('href');
Note: $(this) point to current clicked a tag. So you have something like this:
$(".container").on("click", function(e) {
e.preventDefault();
var currentBox = $(this).siblings(".map").toggleClass("active");
$(".map.active").not(currentBox).removeClass("active");
window.location.href = $(this).attr('href');
});

Replacing href attribute with data-href attribute using Javascript

How can I do that for every 'a' tag in a page. My goal is to use this for Google search results to access results without google redirection (used in the href attribute) since the actual link is stored in the data-href attribute. So using Tampermonkey with the following script didn't work, and I don'k know why:
$('body').append('<input type="button" value="Fix Href Attributes" id="GG">');
$("#GG").css("position", "fixed").css("top", 18).css("left", 770);
$('a').each(function(){
var $currentA = $(this);
var dataHref = $currentA.attr('data-href');
$currentA.attr('href',dataHref);
});
How can I do this?
Your code updating the elements is correct, you're just firing it too soon. Fire it in response to the button being clicked:
$('body').append('<input type="button" value="Fix Href Attributes" id="GG">');
$("#GG").css("position", "fixed").css("top", 18).css("left", 770).on("click", function() {
$('a').each(function() {
var $currentA = $(this);
var dataHref = $currentA.attr('data-href');
$currentA.attr('href', dataHref);
});
});
There is, of course, no reason you need to give it an ID and look it up after appending it:
$('<input type="button" value="Fix Href Attributes">')
.css({
position: "fixed",
top: 18,
left: 770
})
.on("click", function() {
$('a').each(function() {
var $currentA = $(this);
var dataHref = $currentA.attr('data-href');
$currentA.attr('href', dataHref);
});
})
.appendTo(document.body);

jquery get href value and use it as a variable

So I have set up a scrolling code for my website.
<section class="fpage">
<a class="next" href="#view">test</a>
</section>
<section class="cpage">test</section>
In jquery I've got.
$(document).ready(function () {
$('.next').click(function (event) {
var cpage = $(this).find('a').attr('href');
var fpage = $(this).closest('section');
event.preventDefault();
fpage.addClass('anim').delay(500).queue(function(next){
$(this).removeClass().addClass('cpage');
next();
cpage.removeClass('.cpage').addClass('fpage');
});
});
});
I want the var:cpage to take the .next href value (in this case: #view) and use it as the name of it's variable. What have I dont wrong in this instance? And how can I turn the cpage var into #view?
.next is the a itself. you don't need to use .find
var cpage = $(this).attr('href');
OR
var cpage = this.href;
Edit : as cpage is an ID you need to do this to select the element
$(cpage).removeClass('.cpage').addClass('fpage');
As far as I understood, this should solve:
fpage.addClass('anim').delay(500).queue(function(next){
$(this).removeClass().addClass('cpage');
next();
$(cpage).removeClass('.cpage').addClass('fpage');
});
You have a few things out of place but all in all, no biggie.
First,
$('.next').click(function (event) {
var cpage = $(this).find('a').attr('href');
It can't call its self. .next is a class for the a tag, so how can a tag find inner elements with the a tag if it is the only a tag element? jQuery's .find works to find children and grandchildren and such of the element it's called upon. thus this line is just as easy written as:
var cpage = $(this).attr('href');
Second,
cpage.removeClass('.cpage').addClass('fpage');
cpage is only a string variable, not a jQuery object, thus it needs a slight change. Try:
$(cPage).removeClass
I don't know what version of jQuery you are using, but I gave your code a complete scrub down and edit and posted a jsFiddle using the latest jQuery's. Important to note, if you're using an older version, some things might be different, such as .on being .bind or .live in older versions.
jsFiddle
$(function() {
$(".next").on("click", function(e) {
e.preventDefault();
var cPage = $(this).attr("href"),
fPage = $(this).closest("section");
fPage.addClass("anim").delay(500).queue(function(n) {
$(this).removeClass().addClass('cpage');
n();
$(cPage).removeClass('.cpage').addClass('fpage');
});
});
})

Setting a cookie based on the name of the link that is clicked

TLDR When clicking on a link I want to assign a cookie with a name of instrument and a value of the text on the link clicked.
Using Jquery.1.4.2.min.js, Jquery.cookie.1.0.js
I am trying to create a cookie when a link is clicked (will always link to "page.html").
name of instrument
value of the TEXT
So far I am trying to use:
<script type="text/javascript" src="scripts/jquery-1.4.2-min.js"></script>
<script type="text/javascript" src="scripts/jquery.cookie-1.0.js"></script>
Link1:
link1
Link2:
link2
Script:
$('a[href=page.html]').click(function()
{
var name = 'instrument';
var value = $(this).text();
$.cookie(name, value, { expires: 365 });
});
When I click the link it just loads the link and no cookie is set.
Debugging with firebug, firecookie, firequery. No cookie for instrument or anything along the lines is found. Onload I'll hit the
"projects" but not the
"$.cookie(name, value, { expires: 365 });" at all.
Even using the below: (Thanks to Sarfraz)
$('a[href="page.html"]').click(function(e)
{
// prevent default action
e.preventDefault();
var name = 'instrument';
// get link text
var value = $(this).text();
// set cookie
$.cookie(name, value, { expires: 365 });
// now go to link's location
document.location.href = $(this).attr('href');
});
Still will not create the cookie.
If I add a breakpoint onto $.cookie~ even on clicking one of the links it does not hit the
breakpoint nor the document.location.href~.
For Zack:
Pre Render -
<script type="text/javascript" src="http://localhost/tree"></script>
After Render -
"<div class="dtree">
<div class="dTreeNode"><img alt="" src="Images/base.png" id="id0"><a onclick="javascript: d.s(0);" href="home" class="node" id="sd0">Home</a></div>"
This is hackish, but it works for me.
$(document).ready( function() {
$('a.cookier').each( function() {
// Kill the link's link feature.
_href = $(this).attr('href');
$(this).attr("rel", _href).attr("href", "javascript:void(0);");
});
$('a.cookier').click(function() {
var name = 'instrument';
var value = $(this).text();
$.cookie(name, value, { expires: 365 });
// Go places
document.location.href = $(this).attr('rel');
});
});
My markup looks like this:
<a class="cookier" href="hrrrngh.html">Shazam!</a>
I use a similar method for "un-linking" my links on pages that use AJAX but must degrade gracefully.
Note: You'll probably want to pick a classier class than "cookier."
Edit:
You could select those <a>'s in there with any of these, pick whichever doesn't select other stuff on the page.
.dtree img + a
.dTreeNode > a
.dTreeNode a.node
.dTreeNode a[onclick=|javascript].node
var value = $(this);
will assign the jQuery object to value. Use
var value = $(this).text();
or
var value = $(this).attr('href');
Try this:
$('a[href="page.html"]').click(function(e)
{
// prevent default action
e.preventDefault();
var name = 'instrument';
// get link text
var value = $(this).text();
// set cookie
$.cookie(name, value, { expires: 365 });
// now go to link's location
document.location.href = $(this).attr('href');
});
Using the answer from Zack above I changed the element tag.
The only issue is it will set the cookie for whichever link is followed wether it be for the link I want or not but it sets the cookie and works for where it is needed.
IF there is a cleaner approach it would be appreciated.
$(document).ready( function() {
$('a[href="page.html"]').each( function() {
// Kill the link's link feature.
_href = $(this).attr('href');
$(this).attr("rel", _href).attr("href", "javascript:void(0);");
});
$('a').click(function() {
var name = 'instrument';
var value = $(this).text();
$.cookie(name, value, { expires: 365 });
// Go places
document.location.href = $(this).attr('rel');
});
});
Massive thanks to Sarfraz and Zack for all the help at least I have something that works for now ^^

Categories

Resources