Is There A Css Option That Links An Html Image To Itself?
Solution 1:
Expanding off of WillardSolutions' comment...
document.getElementById("myImg").addEventListener("click", function() {
window.open(this.getAttribute("src"));
});
.clickable {
cursor: pointer;
}
<imgid="myImg"class="clickable"src="https://www.w3schools.com/images/compatible_chrome.gif"/>
Open your browser console to see the opening of the URL being blocked...
If you want it to open in a new window/tab use:
window.open(this.getAttribute("src"), '_blank');
Solution 2:
Nice idea, but no, as the commenters above have explained.
What you can do is get the source URL of each image using jQuery and append it to the parent <a>
element. I would do this on page load rather than on clicking the image, as then the images are ready to click.
I would also suggest using a thumbnail version of the image, otherwise it will take ages for the page to load. (If you do that, you will need to put all the thumbnails in a subdirectory and then remove that subdirectory from the link URL using a replace function).
$( document ).ready(function() {
$("img").each(function(){
var imgUrl = $(this).attr('src');
$(this).parent().attr('href', imgUrl);
});
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><a><imgsrc="https://cdn.pixabay.com/photo/2018/12/15/02/53/flower-3876195_960_720.jpg"width="200"/></a>
Solution 3:
Don't use JS for this simple solution...
<ahref="image-src.ext"><imgsrc="image-src.ext"/></a>
if you want the image to be downloadable add the download
attribute to <a>
. It is really no problem and the faster performance solution. And about 'stylish'... forget about stylish in coding :D
Solution 4:
This might be the solution you are looking for.
Here is the fiddle. https://jsfiddle.net/RadekD/bgfpedxv/1/
HTML
<img class="image" src="https://placeimg.com/100/200/nature" />
<img class="image" src="https://placeimg.com/200/200/nature" />
<img class="image" src="https://placeimg.com/300/200/nature" />
JS
var images = document.querySelectorAll('.image');
images.forEach(function(element) {
element.addEventListener("click",function(){
window.location.assign(element.src);
});
});
Post a Comment for "Is There A Css Option That Links An Html Image To Itself?"