javascript - changing href of a link - javascript

I've got a site which includes jQuery-Tabs, so I have a hashtag in my url to get a desired tab displayed:
www.abc.de/site#tab4
On this site I have a link which looks like this:
LINKTEXT
With this link the user can choose an option for a product. The site gets reloaded on click. I want to achieve that on click the string after the hashtag in the url is read out and then this string will be added to the url or the link...
My function looks like this:
function test() {
var info=window.location.hash;
alert(info);
document.getElementById("optionslink").href+info;
return true;
}
So far the function is on click I get an alert-popup which shows the correct hashtag and it's string. But the site gets reloaded without having the hashtag+string added. It looks like this:
www.abc.de/site.html?option=1
It should look like:
www.abc.de/site.html?option=1#tab4
How can I get this working?

You are not changing the href attribute. Try
document.getElementById("optionslink").href += info;
Your code document.getElementById("optionslink").href+info; just has no effect, as there is just the concatination, but no assignment to the href attribute.

Simply change the location:
function test() {
var info=window.location.hash;
window.location = document.getElementById("optionslink").href + info;
return false;
}
LINKTEXT
Another thing, you pass the current anchor to the function, and save the DOM query overhead:
function test(anchor) {
var info=window.location.hash;
window.location = anchor.href + info;
return false;
}
<a href="/site.html?option=1" name="optionslink"
id="optionslink" onclick="return test(this);">LINKTEXT</a>
Note that not using inline scripts at all is the best practice with javascript events.
You should read about addEventListener, you can read about it in MDN

Related

Javascript. How to get the link on page and redirect it?

Good afternoon.
The site has a link element with http://word.site.com/disfhjsdfl
It should be using JS to find this link and perform a redirect to it. It is interested in the option to redirect.
I tried something like this, but it did not work.
window.onload = function () {
var links = document.querySelector ( 'a [href * = "word"]').href;
window.location.replace ( "links");
break
}
You were close, need to get href of the element.
var links = document.querySelector('a[href*="word"]').href;
window.location.replace(links); //As link is varible use it directly
Try
window.onload = function () {
var links = document.querySelector('a[href*="word"]').href;
window.location.href = links;
}
Hope your html may look like instead make it like <a class="link" href="http://word.site.com/disfhjsdfl"></a>
And your js will be
var links = $(".link").attr('href');
window.location.replace ( "links");
You can also achieve the above just by editing a line
var links = document.querySelector('a[href*="word"]').href;

Anchor Tag for sharing URL on Facebook, Twitter etc

I am trying to find a way (JQuery etc.) of auto updating the URL for sharing on Facebook, Twitter etc.
For example:
<img src="../img/facebook.png">
Except I want to replace "http//xxxxxxxxx.co.uk" with something so that if the URL of that page were to change, it would grab that URL and insert it into the tag, without me having to update it manually?
Do you just mean that you want to dynamically build this href from the current page's URL? Something like this?:
document.getElementById('yourAnchorElement').href =
'https://www.facebook.com/sharer/sharer.php?u=' +
encodeURIComponent(window.location.href);
It just gets the current URL, URL-encodes it to be used as a query string parameter, appends it to the known base URL, and sets it to the href of the element.
You don't need to use document.getElementById(), any method you use to identify the target element is fine.
Here is a small function to generate share buttons with jQuery.
HTML
<div id="fb"></div>
jQuery
var fblink = "https://www.facebook.com/sharer/sharer.php?u={{link}}";
$(document).ready(function () {
generateLink('fb','http://www.google.com');
generateLink('fb','http://www.stackoverflow.com');
});
function generateLink(id,link) {
$('#' + id).append('Share');
}
JSFiddle
I replaced you image with "Share" for completeness in JSFiddle without access to your image, but that can be replaced to suit your needs.
Using jQuery you can do something like this on document.ready:
Here is a jsFiddle demo
$(function () {
var fbShare = 'https://www.facebook.com/sharer/sharer.php?u='
// grab url of the page:
var url = window.location;
// loop through all elements with class 'button--facebook' and update href:
$('.button--facebook').each(function () {
$(this).attr('href', fbShare + url);
});
});

Adding an onMouseDown attribute equivalent to each anchor's HREF attribute in a class or document

I'm having trouble getting an onMouseDown function that takes each link and copies the original HREF attribute of its respective anchor tag in a page and loads the URL on the down event.
Let's call this function loadURL().
Right now I'm testing the function in-line for each anchor and am having trouble getting different values for each HREF attribute. I would like to make an onLoad function that essentially adds the onMouseDown attribute and loadURL function to every anchor. Here's the JQuery code I have now.
PROBLEM SOLVED, SHOWING INITIAL PROBLEM FOR REFERENCE
Script:
function loadURL()
{
var url = $('a').attr('href');
location.href = url;
}
function mouseDownerURL () {
$('a').attr('onmousedown', 'loadURL()' );
}
HTML
<body onLoad="mouseDownerURL();">
<a onmousedown="" href="foo.com">Takes you to foo.com on mouseDown</a>
<a onmousedown="" href="bar.com">Leads to foo.com NOT bar.com on mouseDown</a>
</body>
SOLUTION
function mouseDownerURL() {
$(document).ready(function() {
$('a').mousedown(function() {
window.location.href = this.href;
});
});
}
<body onLoad="mouseDownerURL();">
1
2
...
Get rid of all of those functions and onload things and just do it normally:
$(document).ready(function() {
$('a').mousedown(function() {
windows.location.href = this.href;
});
});
Your problem is this line:
var url = $('a').attr('href');
$('a') selects all of the <a> tags, not the one that was clicked. To work around that, you have to pass the element into your function via an argument, but that's not a great idea.

Javascript - how do I minimise this code example?

a quick question.
At the moment I have 12 links on a page, and 12 corresponding javascript codes that run when a each button is clicked.
I know 100% there must be a method of having 1 javascript code and the link passing a variable to it, so I don't have to have 12 different codes.
EG. Here is a link I'm currently using:
Anatomical Pathology
And the Javascript function that is run when the link is clicked loads some html from a php script into a div which is previously defined as level2:
$('#button1').click(function() {
level2.load("http://hello/script.php?url=poodles");
});
What I'd really like to do is something like this with the link:
Anatomical Pathology
And the function something like this, so I only need the 1 function not 12:
$('#button1').click(function() {
level2.load("http://hello/script.php?url=' + passurl + '");
});
How do I go about getting the data from the link tag into javascript, and also how do I add this passed variable into the url I want the javascript to pull data in from?
passurl isn't standard attribute, you should use data-passurl
$('#button1').click(function() {
var passurl = $(this).data('passurl'); // or $(this).attr('data-passurl');
level2.load("http://hello/script.php?url=" + passurl);
});
Why don't you utilize your hash there...
Anatomical Pathology
In your script
$(".button").each(function() {
// get the hash and extract the part we want store it in this enclosure
var url = $(this).attr("href").replace(/^#\//, "");
// create a click handler that loads the url
$(this).click(function() {
level2.load("http://hello/script.php?url=" + url);
});
});
This also brings about the possibility to extrapolate from that so that a hash passed through the url can also operate the script loading...
You can use the rel attributte (or any data- attributes if your using HTML5 Doctype) to save your URL and add a class to the links you want to execute your callback.
Anatomical Pathology
Your Callback:
$('a.button').click(function() {
level2.load("http://hello/script.php?url=' + $(this).attr('rel') + '");
});
For a more extensible solution you could consider making a json structure for your urls:
var urls = [{
"poodle":{
"url":"http://hello/script.php?url=poodle",
"someOtherData":"data"
},
"otherDog":{
"url":"http://hello/script.php?url=otherDog",
"someOtherData":"data"
}
}];
You would store some sort of key somewhere in your HTML element:
Anatomical Pathology
Then you would leverage this data structure in your functional code:
$('a').click(function () {
var key = $(this).attr('rel');
level2.load(urls[key].url);
});
As per Stuie, add a class to the links so that you can target them all at once. However, I don't see the need to fool with the hash, and I wouldn't add a bunch of click events either. Just delegate once and you're done:
<div id="wrapper">
Poodles
Schnausers
</div>
and the JS:
$('#wrapper').delegate('a.button', 'click', function(e) {
e.preventDefault();
var passurl = $(this).attr("href");
level2.load("http://hello/script.php?url=" + passurl); // assuming "level2" is valid from elsewhere
});
Where I have "#wrapper" you would designate any unique selector that is an ancestor of all your links. It's an element that listens for clicks on the a.button elements within.

Change hyperlinks dynamically using jquery

I want to change the param of link dynamically.
For e.g.
Link1
Link2
Link3
by default their url is ?item=text i.e. for link1(href="?item=link1") etc..
but when i click link1 the url of link2 and link3 should be
link2(?item=link2&item=link1)
link3(?item=link3&item=link1)
any idea how to acheive this?
Thanks,
Assuming all the links have a class of superspeciallink, this should work:
$('a.superspeciallink').bind('click', function(){
var querystring = this.search; // The search property of links gives you the querystring section of their href
var originalhref = this.href;
$('a.superspeciallink').each(function(){
if(this.href != originalhref) {
this.href = this.href + '&' + querystring.slice(1);
}
});
return false;
});
This would mean that these links never get followed though — I assume some other JavaScript would be reading out these query string values eventually.
Invoke jQuery something like the following:
$("my#links").attr("href", "new/href/value");
You'll need to write a function to calculate the new value of href for each link, of course.

Categories