Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using javascript variable on html <a>

I have this javascript code:

<script ="text/javascript">
    var newUrl=window.location.href;
    var pathArray="";
    pathArray=newUrl.substr(newUrl.lastIndexOf("?")+1);
</script>

I want to use the pathArray variable as a part of my href on the tag

This is my html code

<a href="game.html?"+pathArray>
  <img src="img/RestartButton.png" style="position:absolute;
  left:80px; top:220px">
</a>

but it seems like it doesn't read the value if the variable, but the name of it instead.

like image 433
Adyana Permatasari Avatar asked Jul 27 '13 05:07

Adyana Permatasari


1 Answers

You're mixing your javascript into your HTML.

I believe your pathArray variable will also not contain what you are expecting.

Try this in your script tag:

var gamePath = "game.html?" + window.location.search.replace( "?", "" );
document.getElementById("gameAnchor").setAttribute("href", gamePath);

And add an id to your anchor:

<a href="#" id='gameAnchor'>

The javascript will get all GET parameters from the current url and then replace the href attribute in the element with an id of gameAnchor with your game.html concatenated with the GET parameters in the url.

like image 127
tchow002 Avatar answered Sep 29 '22 15:09

tchow002