So I have the code below that pulls a 'parameter' from the URL and replaces an ID called 'demo' in my HTML: EXAMPLE: sample.com?demo=test
function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
var demo = decodeURIComponent(getUrlParameter('demo'));
document.getElementById('demo').innerHTML = demo;
Then I have the following code which does the same, except it pulls from a cookie
function getCookie(c_name) {
if (document.cookie.length>0) {
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1) {
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1)
c_end=document.cookie.length;
var cookieContent = "Welcome back " + unescape(document.cookie.substring(c_start,c_end));
document.getElementById('demo').innerHTML = cookieContent;
}
}
}
getCookie('demo');
What I'd like to do is write something that pulls from the parameter immediately, and if a user comes back to the page without the URL parameter, pull from the cookie. I'm thinking this is some sort of IF statement. But I'm confused on how to mesh these two scripts together to work in sync.
So essentially, IF demo
is in URL, insert into any ID that = demo
, if not, look in cookie.
It would also be great if I could add spaces to the parameter. So if the URL: sample.com?demo=this+is+a+test
To have the ID = this is a test
I've figured this out for the most part. BUT, all ID's called 'demo' become 'undefined' within my HTML document. My HTML looks like this: Welcome New User
So I'd like it to display 'New User' or whatever is displayed in the ID IF there is no parameter or cookie set. Hope this makes sense.