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=test@test.com
Desired IMG SRC - <img src="https://www.example.com/example.jpg?email=test@test.com">
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.
Considering this is our URL: https://www.example.com/page?utm_source=test&email=test@test.com";
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 + "'>";
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=test@test.com','email','myImage','image-name.jpeg'); //helper for run function: //setToImg('your_url_whith_params','param','your_image_id','your_image_url_without_params'); //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>
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=test@test.com','email','myImage'); //helper for run function: //setToImg('your_url_whith_params','param','your_image_id'); //for top page url: //setToImg(window.location.href,'param','your_image_id'); 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.