pv619
pv619

Reputation: 409

how to clone url parameter value inside img src attribute?

I am trying to get parameter value from the url, add it inside a div and then clone that value inside the img src attribute.

I can get the parameter value inside a div, and get it to clone as well but it's doing it like this:

<img id="target" src="images/">samplevalue.png</img>

I need to do like it this:

<img id="target" src="images/samplevalue.png" />

Sample parameter: param1=samplevalue.png

here's the code:

html

<div id="block1"></div>
<img id="target" src=""/>

jQuery/Javascript

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return decodeURIComponent(pair[1].replace(/\+/g, "&nbsp"));
        }
    }
    return decodeURIComponent(pair[1]);
}

document.getElementById("block1").innerHTML = 
getQueryVariable("param1");

$(document).ready(function() {
    $("img#target").attr("src", "images/").html($("#block1").html());
});

Even if adding the parameter value straight inside the img src attribute is fine too than adding first inside the div.

Any help on this is highly appreciated. Thank you very much in advance.

Upvotes: 3

Views: 1798

Answers (3)

Mamun
Mamun

Reputation: 68943

You have to add the returned value from the function as part of the attribute src.

With .html($("#block1").html()) on the image element, you are trying to set html on th image which is actually invalid:

Change the function to:

$(document).ready(function() {
  var urlPart = getQueryVariable();
  $("img#target").attr("src", "images/" + urlPart);
});

Please Note:

Since you are already using jQuery, I will suggest you not to mix JavaScript & jQuery if possible, like:

document.getElementById("block1").innerHTML = getQueryVariable("param1");

Could be easily written:

$('#block1').text(getQueryVariable("param1")); //text() is preferred when dealing with text content 

Upvotes: 2

evgeni fotia
evgeni fotia

Reputation: 4810

$("img#target").attr("src", "images/"+$("#block1").html());

Upvotes: 1

Andr&#233; DS
Andr&#233; DS

Reputation: 1901

You should do it like this :

$(document).ready(function() {
    var param1 = getQueryVariable("param1");
    $("img#target").attr("src", "images/"+param1);
    $("#block1").html(param1);  
});

Put your param into a variable and then use it to change your SRC attribute and to put the content into your div.

Upvotes: 4

Related Questions