How to replace the <img src> of a small image with a large image?

Asked

Viewed 21,918 times

16

Information:

I’m trying to make a simple photo gallery. I want to show the large-sized image in the center of the screen. (Clicar em 0.jpg e mostrar em uma outra div 0Large.jpg)

Problem:

With the code I have I can do this, but just really showing the image clicked. The problem is that this clicked image will be of a different size (it will be something like thumbnail) so clicking the image that appears is small. I want to show a great version. Ex: 001Large.jpg instead of 001.jpg. I don’t really know how to do this. I thought I’d use a kind of loop in the variable that contains the address of the image until she found the ". jpg" and insert before this text ". jpg" the name "Large" to display the large version of the image. I have an HTML similar to this:

<div id="gallery-work">
<div id="gallery-warper" >

    <div class="img-container" >
        <img src="img/gallery/work/001.jpg" alt="" width="100%" />
    </div>

    <div class="img-container" >
        <img src="img/gallery/work/002.jpg" alt="" width="100%" />
    </div>

    <div class="img-container" >
        <img src="img/gallery/003.jpg" alt="" width="100%" />
    </div>

    <div class="img-container" >
        <img src="img/gallery/004.jpg" alt="" width="100%" />
    </div>
</div>

And Javascript:

$(document).ready(function () {
    $("img").click(function() {
        var imgLocation = $(this).attr("src");
        var newImgLocation = '<div id="showimg" class="midway-horizontal midway-vertical"><img class="imgshow midway-horizontal midway-vertical" src="' + imgLocation + '"/></div>';

        $(".main-container").append(newImgLocation);
        Midway();

        $("#showimg").click(function() {
            $(this).remove();
        });
    });
});

Example in Jsfiddle

Obs: When clicking on the div containing the large image you should remove the image but Jsfiddle is not working.

5 answers

8


Answer:

First, you must generate the path of your images dynamically, so it is easy to change them dynamically as well.

Explanation:

You can generate the path of your images automatically this way using this function then declare it at the beginning of your JS to use it later:

function setSRCImagens(caminho){
  $('.img-container img').each(function(index){
    $(this).attr('src', caminho+index+'.jpg');
    $(this).attr('index', caminho+index);
  });      
}

And then you can run in the event onLoad or in the documentReady (when your page loads):

setSRCImagens("img/gallery/work/");

To place small images.

And you can run in the event onClick of your images:

var newImgLocation = '<div id="showimg" class="midway-horizontal midway-vertical"><img class="imgshow midway-horizontal midway-vertical" src=""/></div>';
$(".main-container").append(newImgLocation);
$('#showimg img').attr('src', $(this).attr('index')+'Large.jpg');

To put "Large" at the end of the src’s path equal to the small but black box you made and make it big.

Example running on Jsfiddle(does not contain images)

Very Important:

You should make sure your images follow this name order: 0.jpg,1.jpg... and 0Large.jpg,1Large.jpg... onward.

7

The best thing you do is use some specific plugin for this, I recommend the colorbox, you don’t need to break your head by programming the javascript, besides other features, then just customize the css, If this is really necessary, follow a simple example:

<a class="group1 cboxElement" href="img/gallery/work/001Large.jpg" title="Esse title vai aparecer no plugin.">
   <img src="img/gallery/work/001.jpg" />
</a><br/>

<a class="group1 cboxElement" href="img/gallery/work/002Large.jpg" title="Esse title vai aparecer no plugin.">
   <img src="img/gallery/work/002.jpg" />
</a><br/>

<a class="group1 cboxElement" href="img/gallery/work/003Large.jpg" title="Esse title vai aparecer no plugin.">
   <img src="img/gallery/work/003.jpg" /> 
</a>

and in head you call the js and css of it, available for dowload here, also includes the following code:

$(".group1").colorbox({rel:'group1'});
  • Thanks friend, I agree with you, the best thing will be to use even a ready. I wish I could mark your answer as "Answer" but the topic question is to change the SRC and not a way to make a gallery. Eventually I’ll end up using Colorbox anyway. I had already looked at it, but I thought it would be more practical to do something simple, but it’s not as simple as just styling with CSS. Thank you!

  • This is questionable, but it does not fit here, needing we are there!

2

Utilize data Attributes:

html:

<img src="img/gallery/003.jpg" 
     data-large-img="img/gallery/Large003.jpg"
     alt="" 
     width="100%" />

js:

$(document).ready(function () {
  $("img").click(function() {
    var largeImg = $(this).data("large-img");
    alert(largeImg); // img/gallery/Large003.jpg
  }
});

Example jsfiddle

  • Remembering only that the use of data Attributes directly in HTML should be done sparingly in order to ensure main compatibility, but not exclusively, with respect to Internet Explorer which in versions 8, 9 and 10 partially support them. With jQuery, however, since not using jQuery.data() in XML documents (because of IE again), no problems.

2

An easy way to solve your problem is to use Regular Expressions to change the image address without having to modify your code a lot.

Example to find file name which is a number followed by .jpg:

/\/([0-9]+)\.jpg/i     //apenas números
/\/([0-9a-z]+)\.jpg/i  //números e letras

To understand what this expression does use it in Regexper.com.

Applying in your code:

var imgLocation = $(this).attr("src").replace(/\/([0-9]+)\.jpg/i, '/$1large.jpg'); 
// De: img/gallery/work/001.jpg
// Para: img/gallery/work/001large.jpg

var newImgLocation = '<div id="showimg" class="midway-horizontal midway-vertical"><img class="imgshow midway-horizontal midway-vertical" src="' + imgLocation + '"/></div>';

$(".main-container").append(newImgLocation);

2

Most problems whose solution depends on navigating the DOM are solved by structuring the HTML properly. The structure presented by Kenny, used by many plugins like Lightbox, Colorbox among others, solves this problem well with a simple:

$( this ).attr( 'href' );

Inside a jQuery.click() it is already possible to obtain the path of larger image.

Its current structure, although not the most appropriate one, also allows you to reproduce the behavior, you just need to know how to add any string in path of the original image.

All you need is:

  1. Locate the node corresponding to the image
  2. Get your attribute src
  3. Manipulate him
  4. Replace the attribute value src for the new

Behold my implementation

The "trick" here is in locating the last point in the string of path and replace everything after it with the string that distinguishes the large image and the extension of the same.

In this solution it is taken into account that the extension of the large image will be at all times JPG, but if for some obscure reason you have that the large image will keep the extension of the small image, and that the extension of the small image may vary between multiple formats (normal in image upload) just get the said extension before:

src.split( '.' ).pop();

See working on second revision. In this revision I changed the extension of the first image from JPG to PNG so that it was very evident (in the Console, of course) that the original extension was being used.

  • I really think the best way would be to use the HTML that is in Kenny’s answer but without plugin, as you suggest.

  • 2

    Using or not using plugins is always a very delicate and controversial subject, especially with Javascript where everything that’s too much can be (and will end up being) detrimental to performance. This is not the case because with a few lines it was possible to solve the main problem proposed, but if the goal is really a gallery, with effects similar to Lightbox and everything else, there is no need to reinvent the wheel or worse, spend time with the crossbrowser compatibility that renowned scripts have.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.