image rollovers for responsive pictures utilizing the picture element and srcset

Trying to find a way to implement an image rollover effect on the picture element within a responsive website.

The big question is, can we apply an image rollover to the scrset attribute in the picture tag?

An example of an img tag with a JavaScript rollover effect that works:

<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=""/>

An example of a picture element with a JavaScript rollover effect that doesn't work:

<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>

If anyone has suggestions on how to achieve a rollover effect on the picture tag using srcset, please share!

The webpage contains around 12 responsive images that require a rollover effect.

Answer №1

Swapping out the src/srcset values for an image may not be the best approach, as it could interrupt the image download process if the user interacts with it before the download is complete.

Here are a couple of alternative methods that could be considered:

  • Create a duplicate of the picture element using cloneNode(true) and update the URLs on the cloned version. Swap the original and clone based on mouseover and mouseout events.
  • Add a second copy of the picture in the HTML markup to represent the hovered image, with one set to have a hidden attribute. Toggle the visibility of both images as needed.

In the future, it might be possible to achieve this behavior using CSS, such as

img:hover { content:image-set(...); }
.

Answer №2

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');
  })
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The concept of localStorage is not recognized in the next.js framework

Currently working with next.js for frontend development. Facing an issue where I need to access user data from localStorage, but due to next.js being a server-side rendering framework, I am unable to retrieve data from localStorage. How can I solve this pr ...

Tips on ensuring the <script> section of a Vuejs single file component loads prior to the <template> section

After posing my query here, I have come to the realization that the root of my problem might be due to the template loading before the script. This causes an error when it encounters an undefined variable, halting the script execution. The issue could pote ...

What could be causing the audio file not to be received from the front end React to the Python server?

Here is the React code snippet: import React ,{ ChangeEvent, useState } from "react" const FileUpload: React.FC = () => { const [selectedFile, setFile] = useState<File| null>(null); const HandleAudioChange = (event:ChangeE ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

Adding a subtle gradient to the image, just ahead of the SVG

Is there a way to achieve this particular look? https://i.stack.imgur.com/yQjvK.png I'm currently encountering this appearance issue. https://i.stack.imgur.com/eQjQ4.png Any suggestions on how I can make it match my desired outcome? Your assistan ...

Publishing Your App on the Android Market with PhoneGap

Seeking a comprehensive PhoneGap tutorial that covers app publishing, especially struggling with successful app deployment. Currently experienced in HTML, CSS, and JavaScript. Any tips or advice would be greatly appreciated, thank you! I have a good gras ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

Creating a visual that when clicked, reveals an enlarged version at a different location

Is there a way to make an image appear in a different location on the page when it's hovered over? I've searched online but couldn't find a solution using just HTML and CSS. Does anyone know how to achieve this effect? Image not hovered: ht ...

Create a custom route variable in Node.js with Express framework

Is there a way to achieve this particular task using express.js? In my express.js application, I have set up a route like so: app.get('/hello', (req, res) => { // Code goes here }); This setup is functional, but I am curious if it is poss ...

"Step-by-step guide on adding and deleting a div element with a double click

$(".sd").dblclick(function() { $(this).parent().remove(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table width="750" border="0" cellpadding="0" cellspacing="0"> <tr> <t ...

Issue encountered while using AJAX to load images

Currently, I am utilizing a jQuery plugin to fetch images from Flickr. My aim is to organize these images into 3 columns dynamically as they are loaded, ensuring that each image is placed in the shortest column to achieve close to equal lengths for all col ...

How to Automatically Display the First Tab in Bootstrap 3

Having a dynamic modal with two tabs, I aim for #tab1 to always be the default tab upon opening the modal. The issue arises when the modal is opened, #tab2 is clicked, and then the modal is closed. Subsequent reopenings still display #tab2. See JSFiddle e ...

Struggling with a peer requirement for grunt@~0.4.0 during the installation of grunt plugins? Here's how to resolve

I recently tried to set up some Grunt plugins such as grunt-contrib-clean and grunt-contrib-watch using the commands npm install grunt-contrib-clean --save-dev and npm install grunt-contrib-watch --save-dev However, I encountered the following warnings: n ...

Enhance your HTML audio player with added timeline functionality

I'm currently working on incorporating an HTML audio player into my project. I've managed to get the play/pause functionality to work, but now I'm stuck on adding a timeline feature. Additionally, I'm not sure how to implement the play/ ...

Perform an action when a key is held down and when it is released

I am looking to implement a function that needs to be called under certain conditions: It should be triggered every second while a key is being held down (for example, if the key is held down for five seconds, it should fire 5 times every second). If ...

The charts created using chartjs-vue display no data

After following some examples to create a test chart, I am facing an issue where the chart renders blank with dummy data. https://i.sstatic.net/RD77S.png My initial suspicion is that maybe the options are not being passed for the lines, but it seems like ...

Turning my dual button navigation into tabs to display distinct HTML pages beneath a designated header

body{ background:url(background.jpg); background-size: cover; } h1{ font-family: 'Dancing Script', cursive; font-size: 5em; color: white; text-align: center; margin-top: 25px; margin-bottom: 20px; } h2{ font-size: 18px; color: white; text-align ...

Excessive requests to location or history APIs in a brief period of time

Alert: Reached maximum update depth. This issue may arise when a component invokes setState within useEffect without a dependency array, or if any of the dependencies change on each render. const OwnerPage = () => { const onOpen = useAgencyModal((s ...

Operating with JavaScript arrays and objects

My JavaScript array/object consists of the following data: [ { "name": "A", "selected_color": "Red" }, { "name": "B", "selected_color": "Green" }, { ...

Arrange the array so that the item is placed at the beginning while maintaining the original order

Currently facing a roadblock with this particular issue. I am attempting to create a function that accepts an index as input and rearranges the element at that index in an array to be placed at the beginning, while keeping the order of the other elements a ...