source()
A Sniper method that provides a fast, easy and a more robust way to set and get image sources
source() is use to set and get image sources
GET img src
To get the full Image source
$('#img').source() // https://jubbytech.com/sniper/test/images/teacher.jpeg
To get the relative src exactly how it's was set in the code
$('#img').source(false) // ./images/teacher.jpeg
SET img src
Setting a new img src
$('#img').source("images/student.png");
$('#img').source("https://jubbytech.com/sniper/test/images/student.png");
A Callback Function for source()
The Sniper method source()
, also comes with a callback function. The callback function has two parameters:
The original (old) src Object which contains
fullSrc
: the long/complete path.src
: the path exactly as it was set in the code
You then return the string you wish to use as the new image src from the function.
The following example demonstrates source()
with a callback function:
$("button").click(function(){
$("#img").source(function(srcObj){
return '../'+srcObj.src;
});
});
//you can destructure the srcObj
$("button").click(function(){
$("#img").source(function({fullSrc,src}){
return srcObj.fullSrc.trimStart('https://');
});
});
📝 Note: Your function should return a string to be set at the end of the day 🤠
Last updated