Javascript: How to change assets on a dynamically generated page.

by

coffee-beans
Requires: General Knowledge of javascript syntax, string manipulation, and HTML Dom

Problem: Several pages are being dynamically generated on the server side and you need to change an image for each page that is defined in the server side code. The asset on the page does not necessarily have to be an image but this works well for this example.

It is generally preferred to accomplish this on the server side of the web site rather than the client side but this is not always an available solution. A CMS or shopping cart with one template for several products or pages can make it difficult or even impossible to accomplish this on the server. When this is the case you can use a little bit of javascript to accomplish the same effect. First we need a template to work on.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sagittis placerat justo, id dictum neque mollis id. Aliquam sit amet quam eu odio imperdiet convallis. Integer pellentesque, est auctor porttitor venenatis, nisl purus posuere tortor, quis fringilla mi massa in ipsum. Nullam massa metus, faucibus vel convallis vel, blandit id nisl. Morbi et mi at quam fringilla fermentum ac in ipsum. Fusce eget lacus dictum dui accumsan laoreet eu ut libero. Fusce aliquam tempus erat quis imperdiet. Suspendisse potenti. Quisque dictum, elit ut tincidunt egestas, ipsum nisi facilisis est, in iaculis orci felis accumsan nisl. Praesent mattis gravida sapien, a tempor turpis venenatis venenatis. Suspendisse id est vitae mauris tempor mollis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam eu aliquam massa. Etiam mollis, lacus vel dictum dapibus, ligula urna tristique magna, sed ullamcorper libero augue non orci. Quisque viverra sapien vel lorem aliquet lacinia sed at nibh. Etiam ullamcorper consequat ipsum, ac adipiscing mauris tempor ut. Nullam iaculis pellentesque lorem et tempor. Vestibulum aliquam, justo sit amet iaculis venenatis, mauris turpis cursus elit, eu congue purus neque vitae sapien. Donec dui tellus, tempus sit amet euismod in, varius eget ligula. Ut scelerisque, turpis ac malesuada sollicitudin, sem nisl imperdiet diam, a aliquet purus purus sit amet sem. Vivamus viverra, ante nec commodo pulvinar, sapien eros convallis nulla, vitae suscipit erat ipsum sit amet tellus. Nam at est ac odio auctor cursus at sed felis. Nam feugiat cursus justo, vel mollis justo tincidunt at. Etiam eu felis non orci malesuada consectetur. Donec imperdiet nisi vitae tortor aliquam ornare volutpat ligula vulputate. Aenean eleifend nibh ut velit luctus cursus. Suspendisse ornare viverra laoreet. Morbi non nibh in augue porttitor vulputate.
Somebusiness Inc. 2090 W nowhere Dr. Domington, Statesota 14579

Its not pretty but it will do. So we have 3 different urls that all use this template and switch out the content in <div class=”bodyContent”>. We will start with the GET method as this is the easiest of the two variable passing methods to handle. So the urls of our three pages and the image we want in the header are:

http://www.mysite.com/shoppingcart.aspx?productid=1 (headerImage1.jpg)
http://www.mysite.com/shoppingcart.aspx?productid=2 (headerImage2.jpg)
http://www.mysite.com/shoppingcart.aspx?productid=3 (headerImage3.jpg)

As you can probably guess we are going to be using the productid url variable to differentiate between each page and allow us to determine what image we want to display instead of the default image. We can get the whole url of the current page in javascript buy reading the location property of the window object (window.location). After we have this we need a way to extract a url variable.

This function comes in handy for that.

function getUrlVar(varName){
	var endIndex = urlVars.indexOf('&', urlVars.indexOf(varName)+varName.length+1)
//defines end Index as the first instance of the character ‘&’ after the index of the variable name in the url or -1 if ‘&’ is not found.
	if(endIndex == -1)endIndex = urlVars.length;
	//If the ‘&’ character is not found we set the endIndex to the end of the string
	return urlVars.substring(urlVars.indexOf(varName)+varName.length+1, endIndex);
//We return the variable in our url by doing a substring on the url string between end of our varName + 1 (to accomadate for the ‘=’ character) and the endIndex defined above.
}

So we have a function to pull a url var out of this urlVars string but we do not have this urlVars string defined. Well we will want to define this above this function like so.

var urlVars = window.location.href.substring(window.location.href.indexOf('?'));

This will pre-dissect our url into just the part we want to work with, the variable string.

Now that we have a way to grab our differentiator we will need a data source to compare each of the values against and pull the image we wish to display. This is easily done in the template with a multidimensional array (several arrays inside an array to create a table like data source). In our case we will want to make an array like so:

var imgRef = new Array();
imgRef.push(new Array("1", "/someAssetsFolder/ headerImage1.jpg "));
imgRef.push(new Array("2", "/someAssetsFolder/ headerImage2.jpg "));
imgRef.push(new Array("3", "/someAssetsFolder/ headerImage3.jpg "));

A simpler way to depict this that should help with any confusion is to describe it like so.

imgRef = 	[[“1”, 	"/someAssetsFolder/ headerImage1.jpg "],
		 [“2”,	"/someAssetsFolder/ headerImage2.jpg "],
		 [“3”,	"/someAssetsFolder/ headerImage3.jpg "]];

Using these two resources we can use the function to call up what productId we are on and then loop through the imgRef array until we find a match to get our url. We can do this with a simple for loop.

function getImgTag(){ 
    var productId = getUrlVar(“productid”); 
    for(var I=0; I'; 
         } 
    } 
}}

At this point we simply replace the image on the page with the image returned from this function. The easiest way to do this is to assign an id to the image container on the page. Ours is headerImage for this example. So we create one more function to handle the replacement.

function replaceHeader(){
	document.getElementById("headerImage").innerHTML = getImgTag();
}

Now where do we call this function on the page. There are generally two places where it is common practice to put javascript on a page. One is the header which is usually frowned upon, and the other is after the body tag which is what is supposed to be the proper placement. Unfortunately for this example neither of these places will do. If we call this function from the header then javascript will throw an error saying that our headerImage div does not exist yet. If we call it from the footer we will not get a error but the default image can display for a few seconds before it actually switches to the proper image. The best place to call this function is right after the div we want to modify is created in the DOM, in other words, right after the closing tag of our headerImage div. For neatness sake you may want to either externalize the function calls or push them to the header of the page. To accomplish this same goal for POST variables is very similar. The only change is that we do not have a way to grab the variable from the url so we will have to use some uniquely identifiable information on the page. In the case of a shopping cart product I would recommend looking for a serial number or some sort of Identification number. This may adjust the position of the function call as you now need to wait for both the headerImage div to exist in the DOM and the information you are pulling as your differentiator.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>