@FarisPalayi
Posted
Hey, nice job on this oneπ.
You don't need to use js to change the image to make it responsive.
- You can use the html
picture
tag with thesource
tag, and you can set a media query breakpoint using media attribute. It would look something like this:
<picture>
<source media="(min-width:920px)" srcset="desktop-img.png">
<source media="(max-width:400px)" srcset="mobile-img.jpg">
<img src="fallback-img.jpg" alt="image">
</picture>
Or you can use the srcset attribute on the img tag itself.
- And also, if you wanna use
media queries
in js, instead of usingoffsetWidth
, you can use the nativewindow.matchmedia()
method. Like this:
const mediaQuery = window.matchMedia( '( min-width: 768px )' )
if ( mediaQuery.matches ) {
console.log('Media Query Matched!')
}
Learn more: A Complete Guide to CSS Media Queries - css-tricks, window.matchmedia() - MDN
Marked as helpful
@SasaVatic
Posted
@FarisPalayi I appreciate your feedback. It helped me improve my code, thank you!