change image source based on mobile devices - javascript

I am trying to change the image source for devices with small screen size.
I want to target only mobile devices (not desktop browsers) smaller than 1024px width.
I don't want to use media queries since they are going to load both hi and low resolution versions of the image if I change the browser size on desktop. I can target devices separately but it's gonna be huge mess on my css file.
Any proper solution to load smaller images for mobile devices only? (especially smaller than tablets). Also with userAgent it's not easy to target devices like android tablets and android smartphones.
I am using this code but it also causes duplicate file load after I refresh the page.
$(function() {
if($(window).width() <= 1024) {
$(".slides-container li img").each(function() {
$('.slides-container li img').attr('src',function(i,e){
return e.replace("img/galeri/large","img/galeri/medium");
});
});
}
});

Try doing an event handler for window resize:
<body onload="window.addEventListener('resize', setPanels); setPanels();">
function setPanels()
{
var windowWidth = window.innerWidth;
if(windowWidth < 500)
{
document.getElementById('your image').src = 'new image source';
}
else
{
document.getElementById('your image').src = 'new image source desktop';
}
}

$(function() {
if($(window).width() <= 1024) {
$(".slides-container li img").each(function() {
if($(this).attr('src').indexOf("large") > -1){
$(this).attr('src',function(i,e){
return e.replace("img/galeri/large","img/galeri/medium");
});
}
});
}
});

Your issue (as I understand it) is that when the page initially loads, all the images have src="img/galeri/large/...", and you're trying to conditionally change that to be instead src="image/galeri/medium/..." if appropriate for the viewport's width.
Unfortunately, as soon as the img is loaded in the dom, the browser will begin to load the src file, all before your jQuery ever runs.
Given that you evidently have some control over the backend, the lightest weight (albeit quite hacky) solution may be to nuke the src attribute on all imgs on the page, replaced with some other attribute isrc that contains the asset name (the bit after the img/galeri/large or img/galeri/medium), and then step through your image tags on page load like this
$(function() {
var assetLoc = "img/galeri/large";
if($(window).width() <= 1024) {
assetLoc = "img/galeri/medium";
}
$(".slides-container li img").each(function() {
var assetSrc = assetLoc + $(this).attr('isrc');
$(this).attr('src', assetSrc);
});
});
Again, hacky, but it will allow for the asynchronous loading you're looking for with a minimal amount of work.

Related

Different design desktop/mobile devices

I hope there is an answer for this question.
I'm not good at codeing and I hope someone will understand my question.
Is there any way to have 2 different designs..
I have a design for a desktop/ipad and one for mobile devices.
The one for the mobile device is more like the design of an application.
So what I want now is if my javascript code find out that the website is opened on a mobile device, the website turn into the version for the mobile device.
For example:
The desktop/ipad version is the index.html and the mobile version is the mobile.html
is there a way to make a javascript code to go to the mobile version if
if(!is_mobile) {
(function(XXXXX) {
XXXXXX
}
The best practice would be to use a responsive html + css. That would automatically restyle the page based on the device type or screen size.
But if you prefer to do it this way, you can do it like this:
In the header of index.html (before any styles or scripts) you can filter the device that is currently opening the page and forward the user to the mobile html (if he's coming from a mobile device).
<script>
if( /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
window.location.href = 'mobile.html';
}
</script>
Hope it helps.
The following javascript code will be useful:
function adjustStyle() {
var width = 0;
//getting width of webpage
if (window.innerHeight) {
width = window.innerWidth
} else if (document.documentElement && document.documentElement.clientHeight) {
width = document.documentElement.clientWidth;
} else if (document.body) {
width = document.body.clientWidth;
}
//loading css if width less than 600. Make sure your link tag has id "myCSS"
if (width < 600) {
document.getElementById("myCSS").setAttribute("href", "css/mobile.css")
} else {
document.getElementById("myCSS").setAttribute("href", "css/desktop.css")
}
}
//calling the function
window.onresize = function () {
adjustStyle();
}

Turn off JavaScript when screen is a set size

How do I turn Javascript off when my page is viewed on mobiles?
I need a sort of media query that will disable all javascript on a page when viewed on a specific device.
So far I have this but do not know how to actually disable all javascript
if(screen.width < 480) {
// do any 480 width stuff here, or simply do nothing
return;
} else {
// do all your cool stuff here for larger screens
}
Thanks
You could use matchMedia.js (found at https://github.com/paulirish/matchMedia.js) and check if the screen is below a certain size.
Eg.
if (matchMedia('(max-width: 480px)')) {
// Run Code Here
}
You can check the
navigator.userAgent
property with Javascript. This will show the used browser and you can determine if its mobile or not.
Documentation:
userAgent Docs
You can do it also width the viewport width of your users browser in pure Javascript:
var w = document.documentElement.clientWidth;

Link relation query - can I create a javascript relation as well as css?

I have this statement in my webpage that formats a page especially so they can view it better with a small netbook screen:
<link rel="stylesheet" media="only screen and (max-height: 750px)" href="netbook.css" />
My question is, can I do the same with javascript?
I have an array of jquery functions that also change depending on screen size. I'm looking for something like this, I suppose:
<link rel="javascript" media="only screen and (max-height: 750px)" href="scripts_netbook.css" />
Any ideas out there?
Many thanks as always,
Dan
What I would do is something like:
$(function() {
var script_path = $(window).height() > 750 ? '/path/to/file.js' : '/path/to/otherfile.js';
$.getScript(script_path, function() { $(window).trigger('script_loaded'); });
$(window).on('script_loaded', function() {
//run other code requiring those scripts here
});
});
Edit: From your comments, it seems like you want to do:
$(function() {
if ($(window).height() < 750;) {
$('#footer_index').delay(800).transition({y:-155 }, 1000, 'snap');
}
});
This won't work like a media-query as far as resizing, but just on page load. If you want it to work for resizing, you could do something like
$(window).on('resize', function() { //do stuff });
According to Link Types Reference, JavaScript is not a Link Type, so your answer is no.
You can simply use the following for your needs:
screen.onresize = function() {
if (screen.height <= 750) {
//Your scripts
}
};
Note: According to Media Queries 'Height' Spec,
The ‘height’ media feature describes the height of the targeted
display area of the output device. For continuous media, this is the
height of the viewport including the size of a rendered scroll bar (if
any). For paged media, this is the height of the page box.
So to have proper pairing of CSS Media Queries and JavaScript, always use screen.width and screen.height
If you want to follow the style of CSS media queries, you have to use the .resize() function, this is the code:
var resizeBool = ($(this).height() < 750);
$(window).resize(function() {
var resizeBoolTmp = ($(this).height() < 750);
if (resizeBool === resizeBoolTmp) return;
resizeBool = resizeBoolTmp;
//your code that must be updated when the size changes
//from previous comments/answer, maybe this?
//$('#footer_index').delay(800).transition({y: -155}, 1000, 'snap');
});
This code updates the action only when the height limit passed by one or the other side.
Here is a snippet that shows how it works(check console to see what happens when width limit is reached).

Is it possible to resize an Adobe Edge animation?

I'm trying to have an Edge animation resize based on screen resolution. I've made a high-res one for 1080p and higher-res screens, but since the project is reasonably complex, I was wondering if there was a way to export the animation at a different size from Edge, without having to redo everything a few times for smaller screens.
There is also this now which helps scale based on a parent bScaleToParent:
AdobeEdge.loadComposition('MyComp', 'EDGE-985368975', {
scaleToFit: "both",
centerStage: "horizontal",
minW: "0",
maxW: "undefined",
width: "1540px",
height: "3004px",
bScaleToParent: true
}, {dom: [ ]}, {dom: [ ]});
This was helpful: https://forums.adobe.com/message/6939673#6939673
I would try to do it in a DIV or a frame, and use CSS zooming options. Some tips here
I'm going to use CSS3's transform:scale, in conjunction with media queries, to solve this.
I found this to be a great solution.
Add a Resize trigger into your stage. Paste this code inside:
if ($(window).width() < 960) {
if ($(window).width() < 600) {
sym.stop("layout400");
} else {
sym.stop("layout600");
}
} else {
sym.stop("layout960");
}
Then make three different labels in the timeline with the names layout960, layout600 and layout400. Now you can avoid Edge from reloading every time and skip Edge Docks (at least for responsive).
Open up the hi res file, group everything in a div, resize that div to the desired width and height. If there are any image files, make sure to save them at the correct sizes to avoid poor quality browser re-sizes. Save out each version and upload it to a different location on your server.
then put this into the head of the document:
<script>
if ( (960 < screen.width < 1024) && (640 < screen.height < 768) ) {
window.location = 'www.YOURURL.com/ipad';
}
else if ( (screen.width < 960) && (screen.height < 640) ) {
window.location = 'www.YOURURL.com/iphone';
}
</script>
This would redirect based on the screen resolution of an ipad or iphone, but you could adjust it to whatever you like.
Store all your layouts as symbols if you are going to do it using labels and then add them to the stage at run-time. Anything you place on the stage's time line exists in the DOM even though you may not have arrived at a screen marker.

Swap image src if screen width <= 699

I have two images "image-big.jpg" and "image-small.jpg" I want to via javascript detect if screen width <= 699 and change the SRC of my image with class="imageswap" from image-big.jpg to image-small.jpg.
So basically if they are on a portable device it will display the smaller image.
I am novice at best with javascsript and any help is gratefully appreciated!
Bind to the window onresize event:
window.onresize = function(event) {
if(window.innerWidth && window.innerWidth===699)
document.getElementById('myImg').src = 'newSource';
else if(document.body.offsetWidth && document.body.offsetWidth===669)
document.getElementById('myImg').src = 'newSource';
};
The else if is for IE < v.9
Its no in specs but screen works fine in all browsers.
if(screen.width <= 699){
// do you logic
}
1st approach: client-side. Set classname to html tag on dom ready after detection device type. Use css:
html.big .image-div {background-image:url('big.jpg')}
html.small .image-div {background-image:url('small.jpg')}
2nd approach: redirect. Use 2 different URLs and redirect for small size by detection User-Agent. It's better to use User-Agent (navigator object) than window/screen width
Usually I preffer redirects, because you have better code and page look when you can customize it for specific device. It's the way how leaders behave.
Try media-query.
.imageswap{
background-image:url('small.jpg');
}
#media screen and (max-width: 699px) {
background-image:url('small.jpg');
}

Categories