-1

I have the following url

http://www.domain.co.uk/example/#project-471-1747

The end bit #project-471-1747 changes every time a project is saved.

I pretty sure using window.location this can be pulled but what I am struggling to do is find out how to pull and display the full url when a button is clicked.

I'm sure this must be pretty simple to do but It seems to be eluding me!

James
  • 39
  • 8
  • you can use `location.href` – alpheus Mar 28 '17 at 12:07
  • You could use `window.location.hash` it will return **#project-471-1747** or you can use `window.location.hash.replace('#','');` and that will return **project-471-1747** For the full URL `window.location.href` => **www.domain.co.uk/example/#project-471-1747** To find out more open your browser console and paste `window.location` into it. You can see all the window.location properties in the return. – NewToJS Mar 28 '17 at 12:08
  • 1
    It's unclear what you want. If you want the full URL, `String(location)` will give it to you as a string. If you just want the `#project-471-1747` part, that's `location.hash`. – T.J. Crowder Mar 28 '17 at 12:08

3 Answers3

1

Your button markup can be something like this:

<input type="button" value="Display URL" onclick="urlDisplay()">

What this does is, on click of the button, it calls a function called urlDisplay(). You can have something like this in that function to show the full URL:

console.log(window.location.hostname + window.location.pathname);

Of course, you might not want to use console.log. You can choose to append it to some part of your markup.

Rakesh V
  • 146
  • 2
  • 16
0
    <button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = location.href;
    document.getElementById("demo").innerHTML = x;
}
</script>

The above works and does what I need but is there a way to make this auto update every 2 seconds? e.g. so the user does not need to click "try me".

James
  • 39
  • 8
0

just use

var path = window.location.hash;
pckill
  • 3,709
  • 36
  • 48
Arun Redhu
  • 1,584
  • 12
  • 16