Reputation: 35
I am trying to figure out how to apply an image rollover effect to the picture element in a responsive website.
The question is can an image rollover be applied the scrset attribute in the picture tag?
Working example img tag with javascript rollover effect
<img src="media/images/feature-films/tmbs/zen-zero.jpg"
onmouseover="this.src='media/images/feature-films/tmbs/zen-zero-ro.jpg'"
onmouseout="this.src='media/images/feature-films/tmbs/zen-zero.jpg'"
alt=""/>
Not working example of picture element with javascript rollover effect
<picture>
<source srcset="media/images/feature-films/tmbs/zen-zero-large.jpg"
onmouseover="this.src='media/images/feature-films/tmbs/zen-zero-large-ro.jpg'"
onmouseout="this.src='media/images/feature-films/tmbs/zen-zero.jpg'"
media="(min-width: 880px)">
<source srcset="media/images/feature-films/tmbs/zen-zero-small.jpg" media="(max-width: 478px)">
<source srcset="media/images/feature-films/tmbs/zen-zero-medium.jpg">
<!-- fall back -->
<img srcset="media/images/feature-films/tmbs/zen-zero-medium.jpg" alt="">
</picture>
Does anyone have any suggestions hoe to achieve a rollover effect on the picture tag using the srcset?
The web page has about 12 responsive images that need a rollover effect.
Upvotes: 1
Views: 1141
Reputation: 1273
Changing src/srcset is not optimal, even for a single img, since it can abort the download of the image if you hover it or leave it before the download is complete.
I think I would do one of these:
cloneNode(true)
and rewrite the URLs of the clone. When the original picture element receives a mouseover
event, replace it with the clone. When the clone receives a mouseout
event, replace it with the original.hidden
attribute set. Toggle the hidden
attribute on both elements as appropriate.In the future, it should be possible to toggle the image with CSS using something like img:hover { content:image-set(...); }
.
Upvotes: 1
Reputation: 15796
HTML:
<picture id="zen">
<source class="large" srcset="media/images/feature-films/tmbs/zen-zero-large.jpg" media="(min-width: 880px)">
<source srcset="media/images/feature-films/tmbs/zen-zero-small.jpg" media="(max-width: 478px)">
<source srcset="media/images/feature-films/tmbs/zen-zero-medium.jpg">
<!-- fall back -->
<img srcset="media/images/feature-films/tmbs/zen-zero-medium.jpg" alt="">
</picture>
jQuery:
$(document).ready(function() {
$('#zen').on('mouseover', function () {
$(this).find('.large').attr('srcset', 'media/images/feature-films/tmbs/zen-zero-large-ro.jpg');
console.log('mouse over');
})
$('#zen').on('mouseout', function () {
$(this).find('.large').attr('srcset', 'media/images/feature-films/tmbs/zen-zero-large.jpg');
console.log('mouse out');
})
});
Upvotes: 0