I have this HTML
<div class="picture"></div>
and depending on the viewport width, I'd like to add either a small or a large image to the div, so that it will look like this:
<div class="picture"><img src="small.jpg></div>
Here's some jQuery I found somewhere on the web which seems to do exactly what I want. The only part where I'm stuck now is the img src="....jpg" thing. How can I translate this into jQuery?
jQuery(document).ready(function() {
$(window).resize(function() {
var window_width = $(document).width();
if (window_width <= 1024) {
img src = "small.jpg"
} else {
img src = "large.jpg"
}
});
});
Thanks!
If you are creating a <img>
$(window).resize(function() {
var window_width = $(document).width();
if (window_width <= 1024) {
$(".picture").html("<img src='small.jpg'>");
} else {
$(".picture").html("<img src='large.jpg'>");
}
});
or if you just want to assign a source,
$(window).resize(function() {
var window_width = $(document).width();
if (window_width <= 1024) {
$(".picture").find("img").attr("src", "small.jpg");
} else {
$(".picture").find("img").attr("src", "large.jpg");
}
});
You can check if div has img element updated its src else create new img element and append it.
jQuery(document).ready(function() {
$(window).resize(function() {
var window_width = $(document).width();
var imgsrc = "large.jpg"
if (window_width <= 1024) {
imgsrc = "small.jpg"
}
//Picture element
var picture = $('.picture');
//Picture has img element update its src else append new img tag
if (picture.find('img').length) {
picture.find('img').attr('src', imgsrc );
} else {
picture.append('<img src="' + imgsrc + '" />')
}
});
});
Try this code snippet:
jQuery(document).ready(function () {
$(window).resize(function () {
var window_width = $(document).width();
var src = (window_width <= 1024) ? "small.jpg" : "large.jpg";
$('.image').remove(); //Remove in order to avoid multiple images to be added.
$('.picture').prepend($('<img />', {src: src, class: 'image'}));
});
});
Like this :
$('.picture').find('img').attr('src','small.jpg');
You'll need to update the attributes.
In jQuery, you'll do something like this to update the src:
$('<img>') // create a new img node
.attr('src', 'newsrc') // set the src to your desired source
.load(function(){
this.appendTo('.picture'); // once the source has finished loading, append it to the <div>
});
For more information on this, check out this other Stack Overflow post:
Changing the image source using jQuery
Cache both images up front in jQuery objects constructed with image elements pointing to their source.
Then, use your conditional statement to store the string for source and reference it to place the cached image element on the page.
jQuery(document).ready(function() {
//cache images
var imgSet = {
"small.jpg" : $('<img src="small.jpg" />'),
"large.jpg" : $('<img src="large.jpg" />')
};
$(window).resize(function() {
var window_width = $(document).width();
var imgsrc;
if (window_width <= 1024) {
imgsrc="small.jpg";
}else {
imgsrc="large.jpg"
}
//use cached image element
$('.picture').empty().append(imgSet[imgsrc]);
});
});
In jquery you can use append
$('.picture').append('<img src="small.png"/>');
Related
This is an url of video
<iframe src="http://xxxx.com/embed-xxx-720x405.html" frameborder="0" marginwidth="0" marginheight="0" scrolling="NO" width="720" height="405"></iframe>
I got this JS to change width and height in url from 640px:
$(window).on("load", function(event){
var w = $(this).width() -50;
if(w <= 640)
$('.videoimg iframe').each(function () {
$(this).attr('src', $(this).attr('src').replace('720', '' + w + ''));
$(this).attr('src', $(this).attr('src').replace('405', '305'));
$(this).attr('width', $(this).attr('width').replace('720', '' + w + ''));
$(this).attr('height', $(this).attr('height').replace('405', '305'));
})
});
It works with loading a website, but I need that it should work when I flip my phone on landscape so people don't need to refresh the page.
Resize function doesnt work, it should be something like that
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
window.addEventListener("orientationchange", function() {
rvlWidth(w);
}, false);
But I dont know how to do it, do you have any solutions for that?
It seems like the rotation event is set before the 'load' event is fired + 'w' is not defined in the context (at least on the firest time)
try gather the codes as the following
var onRotateCallback = function() {
var screenWidth = $(window).width() - 50;
var videoFrames = $('.videoimg iframe');
if (screenWidth <= 640) {
videoFrames.each(function() {
var frame = $(this);
var originalSRC = $(this).attr('src');
var newSRC = originalSRC.replace('720', screenWidth).replace('405', '305');
frame.attr('src', newSRC);
frame.attr('width', screenWidth);
frame.attr('height', '350');
});
}
};
$(window).on("load", function(e) {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
onRotateCallback();
$(window).on("resize", function() {
onRotateCallback();
});
}
});
I'm trying to get the height and width of the images in the bx slider slides, the problem is that each of them (without the loaded first one) returns zero.
Here is a sample of my code:
$('.slides > li > img').each(function(){
var $this = $(this);
var imgWidth = $this.width();
var imgHeight = $this.height();
console.log(imgWidth);
console.log(imgHeight);
})
I also tried putting them in a on load function like this:
$('.slides > li > img').each(function(){
$this.on('load', function(){
var $this = $(this);
var imgWidth = $this.width();
var imgHeight = $this.height();
console.log(imgWidth);
console.log(imgHeight);
}
})
... but it's still not working =\
Any help will be greatly appreciated!
Edit:
Here's a fiddle: http://jsfiddle.net/a3BUA/1/
Edit 2:
I now see that when the mode is set to fade - the rest of the <li> elements are set to display:none. Is there a way to get the image dimensions despite of this?
The slider hides all but the first image, and hidden images have no dimensions so you have to use the source (literally) to create a new image object, and then get the dimensions from that once the image has loaded
$(document).ready(function () {
$('.normal-slides').bxSlider({
mode: 'fade',
auto: false,
pager: false
});
$('.normal-slides img').each(function () {
var img = this;
var new_img = new Image();
new_img.onload = function() {
console.log('imgWidth = ' + this.width)
console.log('imgHeight = ' + this.height)
}
new_img.src = img.src;
});
});
Try with something like that
$('.slider img').each(function(){
$this = $(this);
var imgWidth = $this.width();
var imgHeight = $this.height();
console.log(imgWidth);
console.log(imgHeight);
});
Fiddle
I have a DIV with background-image. But my requirement is how can I extend the DIV size according to the height and width of background-image. I have tried some code with the help of this link.
var src = $('#divID').css('background-image').
replace('url', '')
.replace('(', '')
.replace(')', '')
.replace('"', '')
.replace('"', '');
$('body').append('<img id="appendedImg" src="' + src + '" style="height:0px;width:0px"');
var img = document.getElementById('appendedImg');
var width = img.clientWidth;
var height = img.clientHeight;
$('#appendedImg').detach();
I am just looking for any elegant solution if possible.
You probably just need to look for width/height onload:
var img = document.getElementById('appendedImg');
img.onload = function() {
var width = img.width;
var height = img.height;
console.log(width,height);
};
Also, you don’t need to attach it, creating a new image should be enough. Here’s how I would do it:
var $div = $('#divID'),
src = $div.css('background-image').replace(/url\(\"([^\"]+).*/,'$1');
$(new Image).load(function() {
$div.width(this.width).height(this.height);
}).attr('src', src);
I would load the img first then get its height and width:
imgSrc = 'http://ajthomas.co.uk/wp-content/themes/ajthomascouk/library/images/logo.png'
// append the temp imag
$('body').append('<img src="'+imgSrc+'" alt="" style="display:none" id="dummyImage"/>');
// get the image width and height
imgWidth = $('#dummyImage').width()+'px';
imgHeight = $('#dummyImage').height()+'px';
// remove the image
$('#dummyImage').remove();
// set the css for the div
$('#imADiv').css({height: imgHeight, width: imgWidth, 'background-image': 'url('+imgSrc+')'});
Coded it up for you here - http://jsfiddle.net/LTdtM/
I have a div for my posts which may contain images with different sizes and i need to set their container's width individually. How do i do that?
<div class="panel">
<img id="screeny" src="http://localhost/531q3n.jpg"/>
</div>
Here's my current try but something's wrong:
var img = document.getElementById('screeny');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
$('.panel').css("width",width+"px");
The image must be loaded before you have access to it's size, like so:
var img = $('#screeny');
img.load(function() {
var width = img.width();
var height = img.height();
$('.panel').css("width", width);
});
EDIT: for more than one image, if they are all in a div with the class 'panel':
$("img", ".panel").each(function() {
$(this).load(function() {
var width = $(this).width();
var height = $(this).height();
$(this).parent().css("width", width);
});
});
$('#screeny').load(function() {
$(this).parent().css('width', $(this).width());
});
Attach a handler that will execute when the image has finished loading. This will set the parent (container) to the width of the image.
I am creating an image gallery of sorts and I want users to have a choice between small, medium, and large thumbnails and have it change without reloading the page. What would the Jaavascript be so that on a mouseclick of a button, all the images with a certain class get resized dynamically?
set up classes for your different sizes.
$('input#small').click( function()
{
$('img').removeClass('large medium').addClass('small');
}
$('input#medium').click( function()
{
$('img').removeClass('large small').addClass('medium');
}
$('input#large').click( function()
{
$('img').removeClass('medium small').addClass('large');
}
var allImgs = document.getElementsByTagName('img'),
allImgsLength = allImgs.length,
className = 'something';
for (var i = 0, i < allImgsLength; i++) {
var image = allImgs[i];
if (image.className.match(new RegExp('\b' + className + '\b')) {
// Set what sizes you need
image.style.width = '400px';
image.style.height = '200px';
}
}
With jQuery:
$('input#foobar').click(function()
{
var newHeight = 200;
$('img.foo').each(function()
{
if ($(this).height() > 200)
{
$(this).css('height', parseInt(newHeight * $(this).css('width') / $(this).css('height')) + 'px');
}
});
});
No guarantees that this will work perfectly, but you can at least build off of it to add different size increments, etc.