Home > OS >  Open any clicked image in a new tab
Open any clicked image in a new tab

Time:07-27

I'm working on a gallery page atm and I want my images to be able to open in new tabs when clicked. I already have a funtion that displays them at full screen width, however that's often too small for the mobile version. Because of that I need a function that can get whatever image is clicked and open it in a new tab. They're all in the same folder but I don't know how to get the file name of the clicked image into the url of the new window.

Currently I have it set so that whenever an image container (.art) is clicked, it pops to full screen, allowing the image inside (.work) to resize while displaying the figcaption.

$('.art').on('click', function () {
    $(this).toggleClass('clicked');
    $(this).find("figcaption").toggleClass('figshow');
})

And whenever an open image is clicked again I want it to open in a new tab. I'm using .work here because you can click outside of the image on the background to trigger the first function again and close the image.

$('.work').on('click', function () {
    if ($(".art").hasClass("clicked")) {
  window.open("images/name");
  }
})

However I don't know how I gan get the url of the <img class=work" src="images/name"> of any given image to be included in the link for the new tab. How can I get it there so it works no matter which .work element I click?

CodePudding user response:

You can simply get the sender of the click event and read its src attribute like this:

$('.work').click(function(e){
    var img = $(e.target);
    var src = img.attr("src");
    window.open(src);
});
  • Related