How replace img based on window size - javascript

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.

Related

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'>");

Add class to image depending on image width

I have a list of images where the width is either 226px or 300px. I want to change the css when the image have the smaller width, 226px. It is the right value on "plus" that should be changed
The HTML looks like following:
<div class="item-image">
<div class="plus-wrapper">
<div class="plus"></div>
<img src="source_to_image" alt="">
</div>
</div>
And it is a loop so it will be several images displayed.
My JS + jQuery so far look like this:
var image = $('.plus-wrapper img');
image.each(function () {
var that = $(this);
if (that.width() < 250) {
that.next('.plus').css('right', '41px');
}
});
But the CSS is not changed. Any idea what I am doing wrong?
Change your code to
$(window).load(function(){
var image = $('.plus-wrapper img');
image.each(function () {
var that = $(this);
if (this.width < 250) {
that.prev().css('right', '41px');
}
});
});
The changes are
use this.width since images have a width property of their own..
use .prev() instead of .next() since the div is the previous element in the DOM
call everything inside the window.load event to be sure the images are loaded (and so they have a width)
You should be using the siblings selector
var image = $('.plus-wrapper img');
image.each(function () {
if ($(this).width() < 250) {
$(this).siblings('.plus').css({'right' : '41px'});
}
});

Avoid loading images in mobiles

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.

How to add a height attribute to img tag?

For example, I have lots of images, all images' original width is 100px, but original height is different. How can I add height attribute based on the original height of these images automatically. Such as
<img src="picture.jpg" width="100" height="132">
<img src="picture.jpg" width="100" height="45">
<img src="picture.jpg" width="100" heighst="321">
<img src="picture.jpg" width="100" height="136">
<img src="picture.jpg" width="100" height="214">
......
I try this, I try to get the original height of each images first,
$(document).ready(function() {
$items = $('img');
$.each($items,function(k, v){
console.log(v.naturalHeight);
});
});
it doesn't work
This works sometimes
$items = $('img');
$.each($items,function(k, v){
$(this).load(function(){
console.log($(this)[0].naturalHeight);
$(this).attr('height', $(this)[0].naturalHeight);
});
});
The problem is that how can I make sure all the images have been loaded before I run the script?
Easiest implementation would be to wait for all the images to load, and then setting the attribute using JavaScript (I notice you're using jQuery).
$(window).load(function(){
$.each($('img'), function(){
// Set the height, hard-style!
$(this).attr('height', $(this).height());
});
});
Obviously, there are other - arguably better - ways to do this (like setting each image's height as it loads), but this should suffice.
Have a look at the imagesLoaded jQuery plugin and maybe wrap the above $.each() in one of it's methods, e.g.:
imagesLoaded( '#yourContainer', function() {
$.each($('img'), function(){
$(this).attr('height', $(this).height());
});
});
If you do not attribute a height, the image will keep its original proportion.
Otherwise, you can do it with JavaScript, like this :
function loaded() {
var img = document.getElementById("imgID");
img.style.height = img.height;
}
EDIT :
If you don't have IDs on your images :
function loaded() {
var images = getElementsByTagName(img);
for(i = 0; i < images.length; i++) {
images[i].style.height = img.height;
}
}
(function(){
$("img.adjust-image").height("100px");
})()
$('img.adjust-image') returns array of all <img>elements that has class=adjust-image class attribute. So We can add the height property for all the images that goes under it.
You don't need to add height attribute at all, only width, and image will scale automatically.

Adding CSS Class According to Image Ratio

I'm creating an image gallery with dozens of landscape and portrait images on a single page. I want to style each image with a dynamically added CSS class (i.e. ".landscape" for landscape images) according to its orientation.
I came across the code below (from 2003!) For determining the ratio and adding a class for a single image, but I need the classes to be added automatically for all images within a certain div id. Honestly, I just don't know enough about JavaScript or jQuery to solve this on my own.
<script language="JavaScript" type="text/javascript">
<!--
function getDim() {
myImage = new Image;
myImage.src="myimage.gif";//path to image
document.divImage.src=myImage.src;
var imgProp;
var width = myImage.width;
var height = myImage.height;
var ratio = width/height;
if ( ratio > 1 ) {
document.getElementById('image').className="portrait";
}
else {
document.getElementById('image').className="landscape";
}
}
//-->
</script>
with jQuery:
$('#divID img').each(function(){
$(this).addClass(this.width > this.height ? 'landscape' : 'portrait');
});
Pretty straightforward jQuery:
$('#yourId').find('img').each(function(i,elem){
var $this = $(this),
ratio = $this.width() / $this.height();
$this.addClass((ratio < 1) ? 'portrait' : 'landscape');
});
See example →
Lets say, that your containing div is of class gallery and you are using jQuery :)
$(document).ready(function(){
$('.gallery img').each(function(){
var width = $(this).width();
var height = $(this).height();
var className;
if (width/height > 1) className = "portrait";
else className = "landscape";
$(this).addClass(className);
});
});
This way is longer, but allows you to add more rules (if there is any reason to do so :).. ie.:
if (width/height == 1) className = "square";
If setting img width/height interferes with your css, you can set it as data-width/data-height:
$('#your-div-Id').find('img').each(function(i,elem){
var $this = $(this),
ratio = $this.attr('data-width') / $this.attr('data-height');
$this.addClass((ratio < 1) ? 'portrait' : 'landscape');
});
HTML:
<div id="your-div-Id">
<img src="#" data-width="60" data-height="30" />
</div>
Edited mVChr's example

Categories

Resources