0

I want to change an image when URL change the parameters.

For example:

http://localhost:8080/h5/informational.html

Don't show anything, but when URL have ?type=parameter, I want to show an image.

I have this code, but it doesn't work.

var img = new Image();
var div = document.getElementById('header');
var url = "http://172.18.43.33:58380/launcher/h5/informational/cabecera.html?type=";
var expansion = url + "expansion";
var experiencia = url + "experiencia";
if (expansion == true) {
  img.onload = function() {
    div.innerHTML += '<img src="' + img.src + '" />';
  };
} else if (experiencia == true) {
  img.onload = function() {
    div.innerHTML += '<img src="' + img.src + '" />';
  };
  img.src = 'images/experiencia.jpg';
} else {
  //Error
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236

1 Answers1

0

if (location.search.indexOf("expansion") !=-1) is a better test. Now you are testing the truthy value of a string - always true when the string is not empty

You likely want this:

var type = "";
if (location.search.indexOf("type=expansion"!=-1) {
    type="expansion";
}
else if (location.search.indexOf("type=experiencia"!=-1) {
    type="experiencia";
}
if (type) {
  document.getElementById('header').innerHTML += '<img src="images/'+type+'.jpg"/>';
}

Using the code from How can I get query string values in JavaScript?

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var type = getParameterByName("type");
if (type) {
  document.getElementById('header').innerHTML += '<img src="images/'+type+'.jpg"/>';
}
Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • you need to use the `location.search` and check for the querystring `type` check [this link](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Zamboney Mar 08 '16 at 13:33
  • I can use location.href to extract the type from the full URL. .search or .href will work the same here. Actually I removed the second parm since it is set in the function – mplungjan Mar 08 '16 at 13:44