Here is a very brief background of what I want to do. I need to create a very small block of JavaScript that will be given to many websites to embed in their home pages. Then, when visitors hit those home pages, a URL will automatically get called that collects certain statistics and returns a small image. I have some of this in place already as follows:
<script>
/* Determine if there is a cookie already exists and get its value if not. */
var userId;
match = document.cookie.match(new RegExp("someUserId" + '=([^;]+)'));
if (match)
userId = match[1];
else {
/* generate a random 10 character string */
userId = (Math.random() + 1).toString(36).substring(5, 15);
/* Store this as a cookie value */
<needs to be done>
}
/* This is what I need help with. A page is called when the home page loads to collect some stats and return a small image */
<a href="http://www.SomeAnalysisSite.com/"><img src="http://www.SomeAnalysisSite.com/Log/?Id=1@userId=xxx" alt=""/></a>
</script>
The piece I don't know how to do is the very last line (with the img tag). I need to generate this dynamically and inserted into the DOM (I think), after the value of "userId" is generated so it can be included as a query parameter in the img src URL. Or perhaps there is a better way? Of course, I'll minify this before it's sent to third party websites.
2 Answers 2
Replace last line with:
document.write('<a href="http://www.SomeAnalysisSite.com/"><img src="http://www.SomeAnalysisSite.com/Log/?Id=1@userId=' + userId + '" alt=""/></a>');
And check if you mean to put & in place of @ in the above line.
Comments
- generate a userId;
- create the url with the new userId;
- create a new img element: document.createElement('img');
- insert a new src attribute img.setAttribute('src', imgUrl);
- create a new a element: document.createElement('a');
- insert a new href attribute link.setAttribute('href', linkUrl);
- insert the "img" inside the "a" link.appendChild(img);
- insert the "a" Element to the dom inside the "somediv" element
var userId;
/*1*/
userId = (Math.random() + 1).toString(36).substring(5, 15);
var siteUrl = "http://www.SomeAnalysisSite.com/"
/*2*/
var imgUrl = siteUrl + "Log/?Id=1@userId=" + userId;
var linkUrl = siteUrl;
/*3*/
var img = document.createElement('img');
/*4*/
img.setAttribute('src', imgUrl);
/*5*/
var link = document.createElement('a');
/*6*/
link.setAttribute('href', linkUrl);
/*7*/
link.appendChild(img);
/*8*/
document.getElementById("somediv").appendChild(link);
<html>
<body>
<div id="somediv">
</body>
<script>
</script>
</html>