skip to Main Content

I’m trying to open an image on click with a simple JQuery.

I’m building on the code provided here:
https://stackoverflow.com/questions/54040130/is-there-a-css-option-that-links-an-html-image-to-itself#:~:text=Nice%20idea%2C%20but,Expand%20snippet

Everything works fine. However, I want to add a detail: the image should open only if the parent doesn’t have an already defined href attribute. Differently the original href should open instead.
Now all the parent of an image get overwritten. How can I avoid this?

On the code below, the first image should open itself. The second one should open the original href.
I want to avoid to use two different classes for the two images. It should be possible to override the href only if undefined using JQuery.
How can I do?

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="script.js"></script>

<a><img src="image2.jpg" class="clickable"></a>
<a href="https://stackoverflow.com/"><img src="image1.jpg" class="clickable"></a>

script.js

$( document ).ready(function() {
    
    $("img").each(function(){
        var imgUrl = $(this).attr('src');
        $(this).parent().attr('href', imgUrl);
    }); 
    
});

2

Answers


  1. PRB!

    Here is one way to do it:

    $('document').ready( document ).ready(function(){
        $('img').each(function(){
            let url = $(this).attr('src');
            $(this).wrap($('<a>',{
                    href: url
            }));
        });
    });
    

    Explanation:

    When the document is ready, it calls for each image tag and then gets the attribute of SRC, which is then added a parent <a> tag, which inturn is the URL for the image.

    I hope this helps!

    Login or Signup to reply.
  2. Select the images that are children of anchors without an href attribute. The best thing is, you don’t need jQuery at all for this

    document.querySelectorAll("a:not([href]) img").forEach((img) => {
      img.closest("a").href = img.src;
    });
    
    // this is just for showing the result
    document.querySelector("pre").textContent = document.querySelector("div").innerHTML;
    /* This is just for the snippet, ignore it */
    div { display: none; }
    <div>
    <a>
      <img src="image2.jpg" class="clickable">
    </a>
    <a href="https://stackoverflow.com/">
      <img src="image1.jpg" class="clickable">
    </a>
    </div>
    
    <pre></pre>

    The jQuery equivalent doesn’t look much different and IMO isn’t worth using.

    $("a:not([href]) img").each((_, img) => {
      img.closest("a").href = img.src;
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search