I have been struggling with dynamically changing HTML content using URL variables. Let me give you an example and than provide you my code thus far.
Ex. I have a landing page with content to be changed. I would like to have a variable in my URL www.domain.com/header=new-content
I would like to be able to rewrite the HTML to show the new header using Javascript or Jquery. Here is what I have thus far. Seems like I am missing the trigger or if/else statement.
Thank you so much!
<script>
var element = document.getElementById("header");
element.innerHTML = "New Content";
</script>
First of all, when you're dealing with URL parameters, you should place a ? before you start defining parameters. This will result in the browser retrieving the page www.foo.bar/ instead of www.foo.bar/header=new-content. Once you add the question mark, you can retrieve URL parameters using the following snippet. I retrieved this from this question.
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];
}
}
}
In your specific case, your final code, after defining the above function, might look something like this:
<script>
var header = getUrlParameter('header');
document.getElementById('header').innerHTML = header;
</script>
This will retrieve the URL parameter header and change the value of the element with ID header to the value contained in the URL. For the URL www.foo.bar/?header=new-content, the element's value would be changed to new-content. If you want to have spaces in the variable, you can remove the URL-encoded characters (ex. %20 for space) by changing the first line in the above snippet to this:
var header = decodeURIComponent(getUrlParameter('header'));
Last minute addition: I just noticed that another answer with more-or-less the same code snippet came in while I was writing this. Whoops. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With