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
PRB!
Here is one way to do it:
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!
Select the images that are children of anchors without an
href
attribute. The best thing is, you don’t need jQuery at all for thisThe jQuery equivalent doesn’t look much different and IMO isn’t worth using.