I'm trying to figure out how can I make one anchor tag that will everytime change when the page is refresh random from the list I have.
Say I have this list
<a href="http://testpage.com/">This is the first one</a>
<a href="http://testpage.com/">This is the second one</a>
<a href="http://testpage.com/">This is the third one</a>
This is the first one This is the second one This is the third one
it is like Link Unit ads that Adsense has but I just want it to do simple random not to do any kind of extra work like check if is relate the topic or not like adsense does.
Please advice me what can I do.
Thanks
JSFiddle
Breakdown
Create an array literal containing three strings:
Get a NodeList of all script elements on the page (as the page has loaded up to this point, so all scripts before and including this one):
Store the last script in that list (IE. this script element) in
this_script
:I'll break this next line up into smaller segments.
Math.random gives a Number between
0
(inclusive) and1
(exclusive). Multiplying it by 3 gives an even distribution between0
(inclusive) and3
(exclusive) and Math.floor truncates it. This gives a random integer between0
and2
inclusive. If you add elements to the array it will update because it uses phrases.length in the calculation, instead of a literal 3:document.createTextNode creates and returns a new Node implementing the Text interface, it's data is just the value that's passed in. In this case it's a random element from the phrases array:
Node.parentNode is self explanatory, in this case the parent of the script element will be the HTMLAnchorElement (that is represented by the
<a>
tag above the script in the tree). Node.replaceChild takes in two arguments, anew_child
and anold_child
. We passed in our new Text Node fornew child
, and this script forold_child
, which causes this script to be removed from the DOM and replaced with the Text Node:You could use php like this: