Embed a javascript variable into my html anchor href - javascript

I have a piece of HTML which should look something like the following when rendered by the browser:
<b>This is a test</b>Test over!
The problem I have is that foo.php is defined in a javascript var in the document. For argument sake, the name of the var is myPath. I'm trying to figure out how to get rid of the hard coded foo.php from the HTML above and have it read it from myPath instead.
I've tried different variations of escaping quotes and document.write() but haven't had much luck.
Is there a way to do something similar to:
<a href=" + myPath + "?bar=yay">
and have it render foo.php from myPath?

If you give your link an ID, you can use that in your JavaScript to reference the element and modify its href.
<a href="#" id="js_link">
And then your JavaScript could look something like this:
window.onload = function() {
var myPath = 'foo.php',
link = document.getElementById('js_link');
link.href = myPath;
}

Just use getElementByID then set the href property.
Check out this working example.
(function () {
var a = document.getElementById('mylink');
var fooLink = 'foo.php';
var link = fooLink + '?bar=yay';
a.href = link;
})();

You should be able to use inline script to output your javascript variable.
This might help How to output JavaScript with PHP

Related

Convert attribute into string

I know this is really basic javascript but I'm really not so familiar with javascript.
What I'm trying here is to add prettyPhoto arguments where I want to be. First I get href attribute from link, then I convert it to string, then I take last 4 letters to check is it link to image or to some HTML page. And this code works fine but still my Firebug sends me an error:
TypeError: $hrefy is undefined
txt = $hrefy.toString();
How script can work if $hrefy is not defined and how to define it well. This error blocks only javascript code for filtering my portfolio, while other js work fine.
$(document).ready(function(){
$("a[data-rel^='prettyPhoto']").prettyPhoto();
$hrefy = $("article a").has('img').attr("href");
txt = $hrefy.toString();
var lastChar = txt.substr(txt.length - 4);
if (lastChar=='.jpg') {
$('article a').has('img').attr('data-rel', 'prettyPhoto');
}
$('a img').click(function () {
var desc = $(this).attr('title');
$('a').has('img').attr('title', desc);
});
});
After looking into the source of the page you've linked, I've noticed that there is no <article> element declared anywhere. So, your jquery selector does not return anything and attr('href') is undefined.

Get current URL and modify subdirectory and then go to URL with Javascript

I'm creating a bilingual website for a client. Two versions of the site in different languages will be created and stored in two folders:
/en/
/chi/
What I want to do is create a link to toggle between the two languages. On the conceptual level, I understand that Javascript can detect the current URL and split it into its different components, modify parts of it (in this case change between /en/ and /chi/), and then go to that new URL when the link is clicked.
But I have zero knowledge in javascript so I have no idea how to execute... I have come across this page:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
but it doesn't explain how to modify and go to the new link.
You help will be greatly appreciated!!
To not break usability considerations like Shift + Click to open in a new window, you should create a plain old link (<a>) that points to the other language URL. There's nothing wrong with building the link via JavaScript, but you could also do it on the server using PHP or whatever templating language you're using.
Here's a script that does this with JavaScript if that's what you decide you'd like to do.
<!DOCTYPE html>
<body>
Content before the link.
<script>
(function () {
// this assumes you're on the en version and want to switch to chi
var holder = document.createElement("div");
var url = window.location.href.replace("/en/", "/chi/");
var link = document.createElement("a");
link.innerText = "Chewa"; // or whatever the link should be
link.href = url;
holder.appendChild(link);
document.write(holder.innerHTML);
})();
</script>
Content after the link.
</body>
If you simply want to take the full URL and replace /en/ with /chi/ or vise-versa, use the code below.
HTML
<span onclick="SwitchLang()">View [Some other Language]</span>
JavaScript
function SwitchLang() {
//Does URL contain "/en/"?
if(window.location.href.indexOf("/en/") != -1) {
//URL contain "/en/", replace with "/chi/"
window.location.href = window.location.href.replace("/en/", "/chi/");
}
//Does URL contain "/chi/"?
else if(window.location.href.indexOf("/chi/") != -1) {
//URL contain "/chi/", replace with "/en/"
window.location.href = window.location.href.replace("/chi/", "/en/");
}
}
Or, a bit more concise (un-commented version)
function SwitchLang() {
if(window.location.href.indexOf("/en/") != -1)
window.location.href = window.location.href.replace("/en/", "/chi/");
else if(window.location.href.indexOf("/chi/") != -1)
window.location.href = window.location.href.replace("/chi/", "/en/");
}
Note: In JS, when you modify window.location.href, the new URL is automatically loaded.
Here's a working fiddle for you to play with.
It looks like you need to change the window.location.pathname. For example:
// assuming the url `http://www.example.org/en/foo/bar/page.html`
var paths = window.location.pathname.split("/");
// change `en`
paths[1] = "chi";
// go to the new url
window.location.pathname = paths.join("/");
See:
https://developer.mozilla.org/en/DOM/window.location

How can I prepend an onclick event with a string of text

I have <a>s with onclick events:
Track Your Package »
How can I prepend those onclick events with http://www.example.com so that the result will be:
Track Your Package »
It has to be compatible with jQuery 1.4.2
Somebody else, had mentioned something like this, but I can't get it to work in 1.4.2:
var link = $("a"); // I don't have enough info to tell you how to precisely get this instance
var originalOnClick = link.attr("onclick");
var part1 = "window.open('"; // this is always the same, right?
var part2 = originalOnClick.substr(part1.length); // the remainder, beginning with TrackPackage.asp
var newOnClick = part1 + "http://www.example.com/" + part2;
link.attr("onclick", newOnClick);
Thanks.
I don't think window.open() is a good idea here. It will get blocked by most popup blockers and if you're using jQuery you shouldn't be using the inline onclick event anyway.
What you're trying to do can probably be achieved with a simple anchor link:
And then you can do something like this:
var prependUrl = function($link, url) {
var oldUrl = $link.attr('href'),
newUrl = url + oldUrl;
$link.attr('href', newUrl);
}
prependUrl($('#yourLink'), 'http://www.example.com/');
EDIT:
If you don't have control over the html and you need to do it like that then use replace() on the onClick attribute like:
$('a').attr('onClick', $('a').attr('onClick').replace('window.open(\'', 'window.open(\'http://example.com/'));
example: http://jsfiddle.net/elclanrs/AH4As/

Fetch and Replace href attribute value of <a> tag using prototype

I have a simple link inside my tml (apache tapestry specific) :
www.google.com
Now on the browser if I am trying to click the link, actually it's redirecting to
http://localhost:8080/..../..../www.google.com
Instead of it should open a new tab for that link.
So the logic which I am thinking is :
1) Fire a javascript on page load
2) Get the href value of anchor tag
3) Append http:// at the start, if it doesn't contains it.
So to do this, actually I want to use prototype (javascript framework), and I am bit new to this...
How can I write the function using the Prototype.js library?
You don't say where the value for your href is coming from. As you say you need to prepend an "http". Assuming the link is dynamically rendered, why don't you just do this server-side, probably much easier. In tml:
... href="${url}" ....
and in .java:
public String getUrl() {
return "http://" + url;
}
This is a much better approach than doing it client-side as what happens if the user has javascript turned off?
On the other hand, if it's a static link in your .tml, just write "http://www.google.com"!
Edit: In light of your comment below:
public String getUrl() {
if (!url.startsWith("http://") {
url = "http://" + url;
}
return url;
}
The above is just an example of what do do. You can either add another method to activityDetails which does this (e.g getExternalLinkWithProtocol()), or provide a wrapper method similar to the one above.
No reason to do this on the client side. Simply change your template to:
www.google.com
and if it's based on a property:
${hostname}
... adjust to fit your properties, etc.
window.onload = function(){
var links = document.links;
for(var i=links.length-1; i>=0; i--){
var link = links[i];
var href = link.getAttribute("href");
if(href.indexOf("http://") < 0){
link.href = "http://" + href;
}
}
};

Get relative path of the page url using javascript

In javascript, how can I get the relative path of the current url?
for example http://www.example.com/test/this?page=2
I want just the /test/this?page=2
Try
window.location.pathname+window.location.search
location.href
holds the url of the page your script is running in.
The quickest, most complete way:
location.href.replace(/(.+\w\/)(.+)/,"/$2");
location.href.replace(location.origin,'');
Only weird case:
http://foo.com/ >> "/"
You can use the below snippet to get the absolute url of any page.
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
}
})();
// Sample Result based on the input.
getAbsoluteUrl('/'); //Returns http://stackoverflow.com/
Checkout get absolute URL using Javascript for more details and multiple ways to achieve the same functionality.
I use this:
var absURL = document.URL;
alert(absURL);
Reference: http://www.w3schools.com/jsref/prop_doc_url.asp
You should use it the javascript way, to retrieve the complete path including the extensions from the page,
$(location).attr('href');
So, a path like this, can be retrieved too.
www.google.com/results#tab=2

Categories

Resources