I am looking for image rotation based on device. Example if website load on desktop it should load desktop.png and if same website load in mobile it should load mobile.png
My JS code :
<script type="text/javascript">
if (screen.width <= 720) {
document.write('<a href="http://example.com/mobile"><img src="mobile.png"></a>');
} else {
document.write('<a href="http://example.com/desktop"><img src="desktop.png"></a>');
}
</script>
I have rewrite the JS code to PHP Code :
if (get($screen, "width") <= 720.0) {
echo "<a href=\"http://example.com/mobile\"><img src=\"mobile.png\"></a>";
} else {
echo "<a href=\"http://example.com/desktop\"><img src=\"desktop.png\"></a>";
}
The above JavaScript code is working fine but my PHP code is giving a error. Can anyone please help to fix it?
My Answer:
javascript
// Check if device is mobile or desktop
function isMobileDevice() {
return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1);
}
// Get image based on device
function getImageUrl() {
if (isMobileDevice()) {
return 'mobile.png';
} else {
return 'desktop.png';
}
}
// Redirect to image URL
window.location.href = getImageUrl();
Rate this post
3 of 5 based on 2038 votesComments