Search code examples
jqueryhyperlinkgalleryhrefimage

each picture in gallery main frame has to have it's own link


I want to make a gallery with thumbnails and a main picture frame, which I managed to do. Now I want to link each picture to different .html. In case shown below all the pictures load c8.html when clicked upon, I only want c8.jpg to link to c8.html, c7.jpg to c7.html etc. From my understanding that problem occurs because "main-img" replaces for example c8.jpg with c7.jpg, and the code switches to <a href="c8.html"><img src="images/gallery/c7.jpg" id="main-img"/></a>.

Thank you for your time and help!

Andraz

<script>
    jQuery(document).ready(function($) {
        $("#gallery li img").click(function(){
            $('#main-img').attr('src',$(this).attr('src').replace('thumb/', ''));
        });
    });
</script>

<div id="gallery">
  <a href="c8.html"><img src="images/gallery/c8.jpg" id="main-img"/></a>
<ul>
  <li><img src="images/gallery/thumb/c1.jpg" alt=""/></li>
  <li><img src="images/gallery/thumb/c2.jpg" alt=""/></li>
  <li><img src="images/gallery/thumb/c3.jpg" alt=""/></li>
  <li><img src="images/gallery/thumb/c4.jpg" alt=""/></li>
  <li><img src="images/gallery/thumb/c5.jpg" alt=""/></li>
  <li><img src="images/gallery/thumb/c6.jpg" alt=""/></li>
  <li><img src="images/gallery/thumb/c7.jpg" alt=""/></li>
  <li><img src="images/gallery/thumb/c8.jpg" alt=""/></li>
</ul>

Solution

  • You'll just have to do the following in the click function

    $('#main-img').attr('src',$(this).attr('src').replace('thumb/', ''));
    $('#main-img').parent().attr('href',$(this).attr('src').match(/c\d/)[0]+".html");
    

    the /c\d/ regexp will match only up to 9, if you have more, you'll have to change that a bit.