Avoid loading images in mobiles - javascript

I want to avoid loading an image on the website when the screen width is lesser than 1146px. I've tried to add the below CSS rule:
#media only screen and (max-width: 1146px) {
#img_cabecera2 {display: none;}
}
And of course, the image is not shown, but it is loaded. I want to load an image only if the screen width s more than 1146px.How could achieve it?
I don't mind if the solution uses CSS, Javascript, jQuery or PHP code.
Edit:
I've achieved it in this way:
template.html:
<div id="img_cabecera2">
<img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" width="0" height="0" alt="">
</div>
script.js:
$(function(){
/* Set img_cabecera2 size */
function set_src() {
var window_width = $(window).width();
if (window_width < 1147) {
$("#img_cabecera2").css({"display":"none"});
} else {
$("#img_cabecera2 img").attr('width', 300).attr('src', "/public/img/carrete.png").attr('alt', "logo").attr('height','auto');
$("#img_cabecera2").css({"top":"15px","left": "44%","display":"block"});
}
}
set_src();
$(window).resize(function() {
set_src();
});
/* ************************* */
...

I use this:
<!-- This image is a blank, 2*2 image -->
<img src="/images/transparant.png"
data-bigsrc="/images/big.jpg"
data-smallsrc="/images/small.jpg" />
With this as javascript
function getProperImageSource(){
var attr2use = $('body').outerWidth()>480 ? 'data-bigsrc' : 'data-smallsrc';
$('img[data-smallsrc], img[data-bigsrc]').each(function(i){
this.src = this.getAttribute(attr2use);
});
}
$(document).ready({
getProperImageSource(); // load images on init
$(window).on('resize', function(){
getProperImageSource();// again on resize
});
});
Might be handy to know: An image on display: none still loads, you just don't see it.
Also, removing images with (javascript-)functions can be slow aswell, because it can still trigger the downloading of the image, but because you removed the <img/> tag It wont be displayed, kinda a waste of time and resource :)

Add the css display:none; to the image and add this jQuery code:
function set_src() {
var window_width = $(window).width();
if (window_width < 1147) {
$("#img_cabecera2").hide();
} else {
$("#img_cabecera2").attr('src', BIG).show(); // Change to your image link
}
}
$(document).ready(function(){
set_src();
$(window).resize(function() {
set_src();
});
});
To avoid the image to be preloaded unnecessarily, while not just having an default empty src="" (omiting an image source is invalid, as I understand it), I found this post where one of the best solutions was to use this only 26 bytes big default source:
src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D"

As has been mentioned, at the moment there is no way of doing this in pure CSS. i have made use of the picturefill script in the past and have found it quite reliable.

Related

CSS attribute not always being grabbed by javascript correctly

I am trying to resize the side bars whenever the image changes.
I have my javascript trying grab the height of the image after it changes
var imgHeight = $('#mainImg').height();
var currImg = 0;
var imagesSet = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg"];
var imageLoc = "images/zalman/"
$('#bttnRight').click(function(){
nextImg();
imgHeight = $('#mainImg').height();
resizeBttn();
});
function nextImg(){
currImg++;
if(currImg>=imagesSet.length){
currImg=0;
}
$('#mainImg').attr("src",imageLoc + imagesSet[currImg]);
}
function resizeBttn() {
$(document).ready(function() {
$('#bttnLeft').css("height",imgHeight);
$('#bttnLeft').css("bottom",imgHeight/2-5);
});
$(document).ready(function() {
$('#bttnRight').css("height",imgHeight);
$('#bttnRight').css("bottom",imgHeight/2-5);
});
}
for some reason, it doesn't always grab the height at the correct time and the side bars will stay at the previous height.
Below I have a JSFiddle that should be working the way my setup is.
Please excuse any inconsistencies and inefficiencies, I am learning.
Just seems weird that it would sometimes grab the height and sometimes not.
I will also be attaching an image of what I see sometimes from the JSfiddle.
I will also attach an image of what I see on my site I am actually writing.
https://jsfiddle.net/6bewkuo5/6/
The issue is because your JavaScript accessing the height of the image before the image as actually been re-rendered in the DOM. Adding a slight delay after assigning the new image source may help things, but...
You actually don't need to use JavaScript to set the height of the buttons
You can achieve what you're after by placing the buttons and image inside of a container with css attribute display: flex.
Like this:
.container {
display: flex;
justify-content: center;
}
<div class="container">
<button class="prev"><</button>
<img src="https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif">
<button class="next">></button>
</div>
Elements within a flex container will automatically fill the height, this includes buttons. Because the images will automatically adjust the height of the container, the buttons will also automatically adjust their height to match.
Run the example below
const images = [
"https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif",
"https://images.sftcdn.net/images/t_app-logo-xl,f_auto/p/ce2ece60-9b32-11e6-95ab-00163ed833e7/1578981868/the-test-fun-for-friends-logo.png",
"https://hiveconnect.co.za/wp-content/uploads/2018/05/800x600.png",
"https://upload.wikimedia.org/wikipedia/commons/b/b5/800x600_Wallpaper_Blue_Sky.png"
]
const imageEl = document.querySelector('img')
let imageIndex = 0
document.querySelector('.prev').addEventListener('click', e => {
if (--imageIndex < 0) { imageIndex = images.length - 1 }
imageEl.src = images[imageIndex]
})
document.querySelector('.next').addEventListener('click', e => {
if (++imageIndex > images.length - 1) { imageIndex = 0 }
imageEl.src = images[imageIndex]
})
body {
background-color: #206a5d;
color: #ffffff;
text-align: center;
}
.container {
display: flex;
justify-content: center;
}
img {
max-width: 50%;
}
<h1>Zalman Build</h1>
<div class="container">
<button class="prev"><</button>
<img src="https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif">
<button class="next">></button>
</div>
The reason is because the resizeBttn code is firing before the image has actually finished downloading and loading into the DOM. I made these changes in your fiddle:
var imgHeight = $('#mainImg').height();
var currImg = 0;
var imagesSet = ["https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif","https://images.sftcdn.net/images/t_app-logo-xl,f_auto/p/ce2ece60-9b32-11e6-95ab-00163ed833e7/1578981868/the-test-fun-for-friends-logo.png", "https://hiveconnect.co.za/wp-content/uploads/2018/05/800x600.png", "https://upload.wikimedia.org/wikipedia/commons/b/b5/800x600_Wallpaper_Blue_Sky.png"];
var imageLoc = "images/zalman/"
$(document).ready(function() {
resizeBttn();
});
$( window ).resize(function() {
/* imgHeight = $('#mainImg').height() */; // commented out; we do this in resizeBttn now
resizeBttn();
});
$('#bttnLeft').click(function(){
prevImg();
/* imgHeight = $('#mainImg').height() */; // commented out; we do this in resizeBttn now
/* resizeBttn() */; // we do this as an `onload` to the image now
});
$('#bttnRight').click(function(){
nextImg();
/* imgHeight = $('#mainImg').height() */; // commented out; we do this in resizeBttn now
/* resizeBttn() */; // we do this as an `onload` to the image now
});
function nextImg(){
currImg++;
if(currImg>=imagesSet.length){
currImg=0;
}
$('#mainImg').attr("src",imagesSet[currImg]);
}
function prevImg(){
currImg--;
if(currImg<0){
currImg=imagesSet.length-1;
}
$('#mainImg').attr("src",imagesSet[currImg]);
}
function resizeBttn() {
imgHeight = $('#mainImg').height()
// removed superfluous doc.ready
$('#bttnLeft').css("height",imgHeight);
$('#bttnLeft').css("bottom",imgHeight/2-5);
$('#bttnRight').css("height",imgHeight);
$('#bttnRight').css("bottom",imgHeight/2-5);
}
And then rewrote your <img /> tag to call resizeBttn on onload:
<img id="mainImg" src="https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif" onload="resizeBttn()"/>
You can see this in action in this fiddle.
Also, a few additional notes on your code, at a glance:
You have some invalid HTML; you're going to want to run that through an HTML validator and fix it, because sometimes it is fine, but sometimes it can lead to all sorts of strange behavior.
You're playing fast and l0ose with global variables in your JS that get set in different functions; it might work OK while the script is small, but as things scale it can quickly become difficult to maintain
You should really avoid abusing the onclick to get link-like behavior from <li> elements; it can impact SEO as well as accessibility. I'd recommend simply using an anchor element inside or outside the <li>
I'd recommend taking a close look at this answer by user camaulay; he makes an excellent point that this may not require JS at all- if a more elegant solution exists w/ CSS it is probably going to be more performant and maintainable.

How to change id of div element when browser resize?

I have this code
<div id="123"></div>
i want to change the id to 234 when the browser resized
<div id="234"></div>
I have use media query , but i think it is not possible
#media screen and (max-width: 479px) {
#123 {
}
}
You can do this easily with javascript or jQuery.
Here a example written in JS.
window.onresize = function(){
var div = document.getElementById("aaa");
if(div){
div.setAttribute("id", "bbb");
}
}
#aaa {
font-size: 10px;
}
#bbb {
font-size: 10em;
}
<div id="aaa">Resize</div>
Im not sure what you are trying to do but this can be solved with window.onresize
You generally shouldn't be changing your element IDs around but if you want to you will need some logic in the onresize function to deduce which ID your element will have when you resize your window.
You're right! It's not possible to do with CSS, but it can be possible to do with JavaScript &/or jQuery. Try this using jQuery:
$(window).on('resize',function() {
$('#123').attr('id','234');
});
The problem with the code above, is that it's a 1x only change. You could never re-target that id after the first resize. So after the browser detects that it has been resized by 2-3 pixels, then the JS will break.
The real question is, why would you want to change an id on resize? It would be better to change an HTML 5 data-* attribute, like: data-id. This allows you to be able to change it repeatedly, using the #myUniqueId attribute. Then your code should continue to run continuously, for as long as the window is being resized.
Here is a jsfiddle for this code:
HTML:
<div id="myUniqueId" data-id="123"></div>
<div id="output"></div>
jQuery:
$(window).resize(function() {
var id = $('#myUniqueId').attr('data-id');
id++;
$('#myUniqueId').attr('data-id',id);
// Double check: what is my id?
var myId = $('#myUniqueId').attr('data-id');
$('#output').html(myId);
});
I use similiar code so you can use different css for mobile or desktop... However it completely irritates me.
This way you use the same id or class. But depending on screen size it will do something different.
#media not all and (min-width:999px){
/* Big Screen */
body {background-color:green; }
#id { background-color:red}
}
#media all and (min-width:1000px)
{
/* Smaller Screen */
body {background-color:blue; }
#id { background-color:grey}
}
Notice how when you manually re size the screen with your mouse the color changes....to the smaller css automatically.
No jQuery answer
window.onresize = function(event) {
if(document.getElementById('123') != null)
document.getElementById('123').id = '234';
};
Just be careful id 234 is not assigned to another element, however you should not be changing your id for changing styles as it should be done by adding and removing css classes.
I hope this one work for you.
//detect window resize
$(window).resize(function() {
//test if window width is below 479
$(window).width() < 479 ? small() : big();
//small function is called when window size is smaller than 479
function small(){
//edited from $( "#id_changer" ).append( "<div id='123'>123</div>" );
document.getElementByID('id_changer').innerHTML = "<div id='123'>123</div>";
}
//big function is called when window size is bigger than 479
function big(){
//edited from $( "#id_changer" ).append( "<div id='234'>234</div>" );
document.getElementByID('id_changer').innerHTML = "<div id='234'>234</div>";
}
});
<body>
<div id="id_changer"></div>
</body>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script src="test.js"></script>

How replace img based on window size

I am trying to replace img src based on window size. This is not a background-image. For mobile size my image needs to be different color/image then larger screens. It is easy to change size of image with css but I think I need to use Jquery to replace image src but cant figure it out yet. Any pointers?
here is my html
<a href="" class="logo">
<img id="brand" src="assets/img/image.png" alt="Image">
</a>
here is my js
$(document).ready(function(){
var windowSize = $( window ).width();
if (windowSize < 400 ) { $('#brand').attr('src', 'assets/img/logo-2.png')};
});
ALL this seems to do is change on load img src not change on window size or resize window.
--edit -- form humbolight
$(function(){
var $window = $(window);
var toggleImage = function toggleImage($el, src){
$el.attr('src',src);
};
$window.on('resize',function(){
if ($window.width() < 385){
//mobile
toggleImage($('#brand'),'assets/img/image.png');
} else {
//landscape tablet/desktop
toggleImage($('#brand'),'assets/img/logo-2.png');
}
});
});
What you are attempting to accomplish would require listening to the resize event on the window element and changing the src based on the changing width (preloading images wouldn't hurt):
$(function(){
var $window = $(window);
var toggleImage = function toggleImage($el, src){
$el.attr('src',src);
};
$window.on('resize',function(){
if ($window.width() < 768){
//mobile
toggleImage($('#two_size_img'),'img#1x.png');
} else {
//landscape tablet/desktop
toggleImage($('#two_size_img'),'img#2x.png');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="two_size_img" src="img#1x.png" />
To accomplish the same end, I would favor toggling a background-image, handled entirely with CSS, or similarly, rendering both elements (one img per image wanted) and showing/hiding the desired image -- again, entirely with CSS.

Load various size images in a fancybox

I have 5-6 images with various sizes like width from 1000px to 1048px and height from 593px to 1736px. But its not loading small images. I tried to pass the width & height but its not working.
HTML
<a class="fancybox" href="images/press/creating websies for NGOS.png" data-fancybox-group="gallery" title="Creating websites for NGOs" data-width="1048" data-height="593">
<img src="images/press/creating websies for NGOS.png" style="border:0" alt="">
</a>
JQUERY
$(".fancybox").fancybox({
beforeShow: function () {
this.width = $(this.element).data("width");
this.height = $(this.element).data("height");
}
});
So how do it. It will load as per the width & height passed from html. Any idea guys ?
The Problem
Your current URL is
http://firstplanet.in/about/feature.php/
and your images are linked to
images/press/commitment to unemployment.png
which gets expanded to
http://firstplanet.in/about/feature.php/images/press/creating%20websies%20for%20NGOS.png
change your image links to
/about/images/press/commitment to unemployment.png
to get them working.
More Info
Read this article on relative URLs. Here is an excerpt.
Not prepending a /
If the image has the same host and the same path as the base document:
http://www.colliope.com/birdpics/owl/pic01.jpg
http://www.colliope.com/birdpics/owl/page.html
We would write < img src="pic01.jpg" >
Prepending a /
If the image has the same host but a different path:
http://www.colliope.com/gifs/groovy14/button.gif
http://www.colliope.com/birdpics/owl/page.html
We would write < img src="/gifs/groovy14/button.gif" >
Part of the problem is the context of this being lost.
Whenever we use this in a function, the context of this takes that function.
So we can assign it early : var $this = $(this);
Edit: Perhaps this.element is a fancybox way to get the element, I don't know, if so, I'm wrong. Nontheless, here's what we can do , if you want to make use of those data height and width attributes:
$('a.fancybox').on('click', function (e) {
e.preventDefault(); /* stop the default anchor click */
var $this = $(this); /* register this */
$.fancybox({
'content': $this.html(), /* the image in the markup */
'width': $this.attr("data-width"),
'height': $this.attr("data-height"),
'autoDimensions': false,
'autoSize': false
});
});
Try this out here
Also some CSS will help keep the fancybox frame from scrolling ( for this direct image usage )
.fancybox-inner img {
display:block;
width:100%;
height:100%;
}
Try
$.fancybox("<img src='images/press/creating_websies_for_NGOS.png' style='border:0'>");

Wait for image full load on ajax action

On my page there is ajax action, which loads div, that contain image on left and text on right.
The problem: first of all text loads, and on the left (it aligned left), then image loads, text shifts on right, and that looks really not smooth.
I tried something like :
$('div#to_load').ready(function() {
$('div#to_load').fadeIn();
});
but that doesn't help.
What can I do?
Update
I think you have to try this trick found here :
$("<img />", { src:"thelinkofyourimage"}).appendTo("div#to_load").fadeOut(0).fadeIn(1000);
Have a look to this fiddle : http://jsfiddle.net/qYHCn/.
You could track when all the images have loaded like so
var element = $('div#to_load');
var images = element.find('img');
var count = images.length;
for( var i = 0; i < count; i++) {
$(images[i]).load(function(){
count--;
if( count === 0 ){
element.fadeIn();
}
});
}
You could smoothly animate it in with jQuery (handy anyway when you are doing your ajax requests with jQuery):
jQuery
$("body").prepend('<img src="http://placehold.it/150x150" alt="img">');
$("img").animate({
opacity: 1,
left: 0
}, 700);
CSS
img {
float: left;
margin-right: 0.8em ;
left: -300px;
position: relative;
}
Fiddle.
Try to load image and text separately, not at once.
And for the shifting problem put image inside another div and define the size when it loads. Then text can't come to image space since we already giving space for image div.
sample code
$('#ImageID')
.load(
function(){
//Do stuff once the image specified above is loaded
$('#textId').html('your text');
}
);
If you don't want content to shift, you must declare the size the image will take up so that the required space is already accounted for when the browser does it's render.
Make sure you declare the size of the image, or the size of the container before you load
<div id="to_load">
<img src="...." height="400" width="400" />
</div>
or
<div id="to_load" style="height:400px;width:400px;overflow:hidden">
..dynamic content
</div>
Declaring image size either on the img element or in your stylesheet is a best practice recommendation anyways
Reflows & Repaint
Maybe you'd like something like this
#to_load {
width: 523px;
height: 192px;
}
#to_load img {
display: none;
}
setTimeout(function() {
$("<img />", { src:"http://ejohn.org/apps/workshop/adv-talk/jquery_logo.png"})
.on('load', function(){
$(this).appendTo("#to_load").fadeIn(500);
});
},1000);
http://jsfiddle.net/AWntU/

Categories

Resources