I'm using lightbox2 on my site and I want my viewers to download the image. The button works, it links to /view/directory/image.jpg and the download button shows just the image. In PHP I made a scripts that downloads the image and sets download+1 in mysql, the only thing i'm not so good at is JS.
Current JS code in lightbox2 is :
this.$lightbox.find('.lb-download').on('click', function (e) {
window.open(e.target.href)
});
Which links to /view/directory/image.jpg because of the href whitch shows the image. I want the lb-download button to go to / download /directory/image.jpg , I already got the download working, just not the window.open and preg_replace part in JS.
You can simply replace the word view
with download
by running the following -
var urlToBeOpened = e.target.href.replace('view', 'download');
window.open(urlToBeOpened);
You can replace the part in the url with word view to download like this:
this.$lightbox.find(".lb-download").on("click", function (e) {
window.open(e.target.href.replace("/view/", "/download/"))
});
url=e.target.href;
url=url.split("/");
url[0]=url[0]+"/download";
url.join("/");
window.open(url);
you got e.target.href
that contains "domain.com/view/directory/image.jpg" and you need it to contain "domain.com/download/directory/image.jpg" so you'll have to do:
JS:
let dwHref = e.target.href;
dwHref = dwHref.split("/");
dwHref[1] = "download";
dwHref.join("/");
window.open(dwHref);
this converts e.target.href
to an array, then you exchange "view" for "download" (position 1 in the array) and then open the window...
Another approach solving this question is using pattern and replace function
Make a pattern like
var pattern = /view/ig;
then assume we have a string like
var a = "domain.com/view/directory/image.jpg";
now simply with replace we can replace any word in that URL
a = a.replace( pattern, "download" );
here is an example https://jsfiddle.net/mhadaily/0zpekx6t/1/
Note: you can easily change a to e.target.href and apply replace function on that.
Notice: i flag in above pattern means single and g flag makes that global to be applied.
for more infromation please read : https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
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.