Time ago I had a header implemented with a Bootstrap carousel: You know, something like this:
<div class="carousel">
<div class="item"><img src="pic1.jpg"></div>
<div class="item"><a href="example.com"><img src="pic2.jpg"></a></div>
</div>
Pay attention to that link on "pic2.jpg", this will be fun...
Recently, I have been asked to use <picture>
elements, so now it is posible to display images for mobile devices:
<div class="item">
<picture>
<source media="(max-width: 576px)" srcset="pic1-small.jpg">
<img src="pic1.jpg">
</picture>
</div>
<div class="item">
<picture>
<source media="(max-width: 576px)" srcset="pic2-small.jpg">
<img src="pic2.jpg">
</picture>
</div>
And here is the tricky question: I need to add a link only in the mobile image (pic2-small.jpg).
(Well, in fact could be links on every image, or none at all, only in the mobile image, only in the desktop image... This is managed by the administrator user)
So, I can't do this because the link should be only for pic2-small, not pic2:
<div class="item">
<a href="example.com">
<picture>
<source media="(max-width: 576px)" srcset="pic2-small.jpg">
<img src="pic2.jpg">
</picture>
</a>
</div>
What I did is this:
<div class="item" onclick="header_onclick(this)">
<picture>
<source media="(max-width: 576px)" srcset="pic2-small.jpg?target=pic2-small-link">
<img src="pic2.jpg">
</picture>
<a id="pic2-small-link" href="example.com" style="display: none"></a>
</div>
<script>
function header_onclick(carousel_item)
{
var current_src = carousel_item.querySelector("img").currentSrc;
if (typeof current_src === "undefined") {
return;
}
var src_parts = current_src.split("?target=");
if (src_parts.length < 2) {
return;
}
var link = document.getElementById(src_parts[1]);
if (link) {
link.click();
}
}
</script>
- An
onclick
event in the carousel item and a javascript function. - A
target
value in the URL of the image. - A hidden
<a>
with the destination URL.
The magic is in this line:
var current_src = carousel_item.querySelector("img").currentSrc;
currentSrc
has the URL of the image that the browser is currently showing according to the screen size. So, from that URL I take the target
parameter and use it to get the corresponding link and then execute it.
All this is working, but I feel it too hacky for my taste. I'm not very experienced with the <picture>
element, so my question is: this could be resolved in a better way?