Reputation: 167
I have a link and I want to add a random number after this link every time that page is load.
How can I do this?
Is there a way to add random number in href tag without any separate jquery code?
i wrote the below code but it does not work.
<a href="secondpage?rand=+Math.Random()">click</a>
Upvotes: 1
Views: 2722
Reputation: 138447
You cant just mix in javascript somewhere on your page. It must be inside a certain area, e.g. the onclick property:
<a onclick="location.href = `secondpage?rand=${Math.random()}`">click</a>
Because this is usually a bad idea, we could have a script that modifies all links on the page and adds the random number:
<script>
window.onload = () => {
document.querySelectorAll("a").forEach(link =>
link.href += "?rand=" + Math.random()
);
};
</script>
Upvotes: 4
Reputation:
The syntax for random number generation is Math.random()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
In order to assign the random number to the href manipulate the DOM.
Here is an example:
<html>
<body>
<div id="foo"> </div>
<script>
var a = document.createElement('a');
a.href="secondpage?rand="+Math.random();
a.innerText = "click";
var div = document.getElementById('foo');
div.appendChild(a);
</script>
</body>
Upvotes: 0