Anchor with a "computed" URL

I have a JS script that adds pairs to the HTML page: input + anchor

Is it possible to compute the URL before the redirect occurs?

Now I have a link that looks like this:

<a href="#" onclick="myFunct();return false;">link</a>

and myFunctuses window.location.hrefto redirect the web page. The problem with this approach is that I cannot (obviously) CTRL + click the link to open the target link in a new tab.

Details:

  • The URL of the link is known after receiving the URL from the server - this operation is very expensive for me, and I would like to do this only if it is absolutely necessary.

  • The idea is this: the user selects the link, he clicks on it, the URL is received from the server, and the user is redirected (in the same window or in a new tab if he uses CTRL + click)

Thank!

+5
source share
4 answers

I solved the problem with precalculating the link and optimizing the code to make the overhead as low as possible.

0
source

I'm not quite sure that this is what you are looking for by anchoring id

<a href="#" id="mylink">link</a>

then just update the attribute hrefto change the new location (perhaps when changing at the input?

<input onchange="changeLink(this)" value="http://www.google.com/"/>

function changeLink(elem) {
    var mylink = document.getElementById('mylink');
    mylink.href = this.value;  // you could prepend your value with a domain
}

Each time the value in inputchanges, the href value will be changed in accordance with

+3
source

onmousedown, href

<a href='http://www.google.com' id='computed_link' onmousedown='handleClick()'>Computed Link!!</a>
<script type='text/javascript'>
function handleClick()
{
    document.getElementById('computed_link').href = 'http://www.yahoo.com';
}
</script>
+3

function myFunct(link)
{
    return 'http://' + link + '#hash';
}

$('a').each(function(){
    $(this).attr('href', myFunct( $(this).text()) );
});​

http://jsfiddle.net/MpM6Y/

You can do the same without jQuery (and more pain) by using var a_list = document.getElementsByTagName('a');and loop through a_listwitha.href = myFunct( a.innerHTML);

0
source

All Articles