I'd like to use JS or JQuery to grab a specific URL parameter and append it to an IMG SRC tag I have embedded in a custom code block on my landing page. Example below:
Example URL - https://www.example.com/page?utm_source=test&[email protected]
Desired IMG SRC - <img src="https://www.example.com/[email protected]">
I've combed through a couple of articles that present similar solutions (usually the image src URL itself), but I haven't been able to get it to work - just out of my depth.
Thank you.
CodePudding user response:
Considering this is our URL: https://www.example.com/page?utm_source=test&[email protected]";
const url = window.location.href;
const email = url.split("email=")[1];
const imgSrc = "https://www.example.com/example.jpg?email=" email;
const imgTag = "<img src='" imgSrc "'>";
CodePudding user response:
With the help of danish's answer:
$(document).ready(function () {
function setToImg(url,param,imageId,imageUrl){
const urlParam = url.split('' param '=')[1];
const result = decodeURI(urlParam).trim();
const imgSrc = imageUrl '?' param '=' result;
$('#' imageId).attr('src',imgSrc);
}
setToImg('https://www.example.com/page?utm_source=test&[email protected]','email','myImage','image-name.jpeg');
//for top page url:
//setToImg(window.location.href,'email','myImage','image-name.jpeg');
console.log($('div').html()); //for test - remove this line.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><img id="myImage"></div>
helper for run function:
setToImg('your_url_whith_params','param','your_image_id','your_image_url_without_params');
UPDATE: for get image past src and append new src:
$(document).ready(function () {
function setToImg(url,param,imageId){
const urlParam = url.split('' param '=')[1];
const result = decodeURI(urlParam).trim();
const imageUrl = $('#' imageId).attr('src');
const imgSrc = imageUrl '?' param '=' result;
$('#' imageId).attr('src',imgSrc);
}
setToImg('https://www.example.com/page?utm_source=test&[email protected]','email','myImage');
//for top page url:
//setToImg(window.location.href,'email','myImage','image-name.jpeg');
console.log($('div').html()); //for test - remove this line.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><img id="myImage" src="https://example.com/img/image.jpeg"></div>
helper for run function:
setToImg('your_url_whith_params','param','your_image_id');