I have two sightly templates- mobile.html and desktop.html and these 2 templates are called from a common file.
I want to call the desktop.html only for desktop mode and the mobile.html for mobile mode.
I am trying to call a js file using js Use API from this common file which should return a boolean value based on some calculations using window.innerWidth so I can use data-sly-test and call the templates based on it.
But the if condition for window.innnerWidth is not working.
Is it because of the use API the window.innerWidth is failing?
If not, what else could it be ? Anybody who has tried implementing similar use case
Note : I am trying to avoid Java and would want to use javascript.
Solved! Go to Solution.
Views
Replies
Total Likes
Your approach is wrong, you forgot about the caching.
you have to have content from both template and show/hide at client side based on device.
Hi @SHIBANI06 ,
you can try the simple script below for detecting the mobile or desktop view port in javascript
if (document.documentElement.clientWidth <= 768){
//For Mobile Portrait
}else{
// For Desktop
}
Instead of having separate html for each view port , you can have one html and make it responsive with css/js. Just a suggestion.
Your approach is not right. First you need to understand what is js use API- it's server side javascript. It does not execute at client browser. I suggest you use AEM's layout/ emulators/ breakpoints to tailor device based user experiences -[0]. You can opt to hide/ show certain components depending on breakpoint you wish to do so.
Regarding how to identify device at client side js- I would prefer smarter way to do that like this one below-
const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)
1. You could use, its a very useful object in many cases
navigator.userAgent or navigator.appVersion
navigator.userAgent or navigator.appVersion
eg:
navigator.userAgent.match(/Android/i) != null
navigator.userAgent.match(/iPhone/i) != null
2. you can also use-
window.matchMedia('only screen and (max-width: 768px)').matches;
3. you could use- navigator.userAgentData too, however, may not be so reliable to use.
function isMobileDevice() {
return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1) || (screen.width < 768);
}
Your approach is wrong, you forgot about the caching.
you have to have content from both template and show/hide at client side based on device.
Views
Likes
Replies