Matu Matu - 11 months ago 39
Javascript Question

Changing content on a page using javascript via a url string

I'm a designer not a JS coder so any help would be great on this.

Using javascript or jquery how would I replace content on a page via a string in the url?

So if content 'A' is just the normal content via this
and if 'A' is replaced by content 'B' via this


content A

<div id="video-player">
vimeo code

to be replaced with content B

<div id="video-player">
youtube code

via a string in the url like so
if there is no string in the url then it will default and just show the vimeo code


ok this is what is on my html page now

<html xmlns="">

<script type="text/javascript" src="js/test.js"></script>


<div id="video-player">


and in js page

var content_value = window.location.hash.substring(1) // For hashses OR
var content_value = window.location.href.split('?')[1].split('&')[0].split('content=')[1] // For ?
if (content_value === "b") {
} else {

is that right?

Answer Source

The easiest wat to do this would be to use a hash tag. You could use a ? but it is harder to implement. So instead of index.html?content=b use index.html#b and then you can reference to that by using window.location.hash.substring(1) which would give you b in your scenario. Then you can use an if statement to check this value and adjust the content accordingly.

Alternatively, if you need to use ? then you can use this window.location.href.split('?')[1].split('content=')[1] but it is not guaranteed to work in every situation, especially if you have more than one variable there. For multiple variables you would use


Your complete code will now look like this:

$(function () {
  var youtube_code, vimeo_code, content_value;
  youtube_code = "The code for Youtube goes here";
  vimeo_code = "The code for Vimeo goes here";
  content_value = (typeof window.location.href.split('player=')[1] !== "undefined") ? window.location.href.split('player=')[1] : "";

  if (content_value === "youtube") {
  } else {

You could also use some else ifs if you wanted more content options. Use one of the top two lines depending on what option you chose.

EDIT: changed code to the complete code (and optimised a bit). You do not need to add anything else to this apart from changing the youtube_code and vimeo_code to the correct values.

EDIT: optimised and made it check if there is actually player= in the url.