How can I make a customized background-image for a <div> in the <head> based on variable passed from URL?
I am trying to allow very primitive customization based on being able to pass a variable through the URL. For example, if they come to my site through the following:
http://my.stackexchange.com?c=alpha
I would be able to display an image, either as an tag or as a background-image, whatever is feasiable, cal开发者_开发百科led image-a.png
But if they come through with a different value:
http://my.stackexchange.com?c=beta
Then the image is different.
This would be easier server side, but was wondering if there are ways to do that by, say, using javascript that I can call in the custom header for example. Or some other ideas?
Yes, this has already been placed on meta.stackexchange.com, but I am wondering if there are ideas from the broader programming community on how I can accomplish this with the constraints of only being able to do put html (and limited javascript it seems).
Thanks.
First get your URL parameters with jquery...
Get escaped URL parameter
... or just javascript...
How can I get query string values in JavaScript?
Now that you have the parameters you can use jquery to modify your image tag src parameter...
Change the image source on rollover using jQuery
You can do this without using jquery as well, but I'd go the jquery route because it sounds like you may have complex javascript needs.
You can view the get parameters (in this case, the "c") from javascript and use javascript to change the src of the img tag to whatever you want.
Check JQuery out...jquery.com
Here is an example from someone that may be close to what you need. http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
That shows you how to get parms...then you could use simple JQuery to load a diff image.
Assuming you will have only one parameter c
, you can get it with the following line:
var c = /\?c=(.*)/.exec(document.baseURI)[1];
That should work in the perfect cases: only one and only properly-formatted parameter c
. If no parameter, it would raise an error.
A more general way could be:
function getURLParameter(key) {
var ret = (new RegExp('[?](\?:.*&)*'+key+'=([^&#]*)','')).exec(document.baseURI);
return ret?ret[1]:null;
}
You can call that when the document loads and change the image accordingly. (that part should be pretty easy though)
精彩评论