I am trying to use modernizr so I javascript can detect if the browser supports object-fit and object-position. The code I got from modernizr works fine, but if it detects something like no-object-fit I want to execute this bit of code:
if (!Modernizr.objectfit) {
$('.wrapper__figure').each(function() {
var $container = $(this),
imgUrl = $container.find('img').prop('src');
if (imgUrl) {
$container
.css('background-image', 'url(' + imgUrl + ')');
}
});
}
I don't seem to get this working. No changes are made inside of the browser if I check in developer mode(I am only testing this in IE. All the other browsers don't need this). I think that it has something to do with adding .css('background-image', 'url(' + imgUrl + ')'); to the $container, but I am not realy sure if this is the case or something else
Its attr not prop - because src is an attribute, not a property.
if (Modernizr.objectfit) {
$('.wrapper__figure').each(function() {
var $container = $(this),
imgUrl = $container.find('img').attr('src');
if (imgUrl) {
$container.css('background-image', 'url(' + imgUrl + ')');
}
});
}
Related
I have some html that looks like this:
<div class="nmMap-wrapper">
<div id="draggable" class="nmMap-image">
<div class="nmMap"></div>
</div>
</div>
and on the "nmMap" I have a background image set in the css.
I then have a javascript loading the background image, appdending it as a image, and then getting the width and height, and alerting all the diffirent variables.
The script looks like this:
jQuery(window).load(function($) {
sceneConstructor();
});
function sceneConstructor() {
var bgHeight;
var bgWidth;
var bgAspectRatio;
function init() {
getBgSize();
alertRatio();
}
function getBgSize() {
var bgsrc = jQuery('.nmMap').css('background-image')
.replace('url("', '')
.replace('url(', '')
.replace('")', '')
.replace(')', '')
.replace('"', '')
.replace("'", '');
var bgImg = jQuery('<img />');
//bgImg.hide();
jQuery('.nmMap').append(bgImg);
bgImg.attr('src', bgsrc);
bgImg.bind('load', function() {
var width = jQuery(this).width();
var height = jQuery(this).height();
alert('first height' + height);
setAspectRatio(width, height);
});
}
function setAspectRatio(width, height) {
alert('second height: ' + height);
bgHeight = height;
bgWidth = width;
bgAspectRatio = bgWidth / bgHeight;
alert('trejde: ' + bgHeight);
jQuery('.nmMap').addClass('ration');
}
function alertRatio() {
alert('bgheight ' + bgHeight);
alert('bgwidth ' + bgWidth);
alert('bgheight ' + bgHeight);
alert('bgaspect ' + bgAspectRatio);
}
init();
}
All this working in firefox, except that the first alert in alertRatio() always gets undefined. But in safari, chrome, and IE, it's like alertRaiom() is being run first, and because of that all the alerts are undefined.
Can someone help and tell me whats going on?
try the default .ready from jquery.
this code load after the dom is loaded.
jQuery( document ).ready(function() {
sceneConstructor();
}):
you can also
jQuery( window ).ready(function() {
sceneConstructor();
}):
source: https://api.jquery.com/ready/
Does it help if you bind() the event listener before you set the image's src attribute?
I am using jQuery to
dynamically create an iframe,
hide the page content,
append the iframe to a hidden div,
calculate the height of the iframe,
set the hidden div to have a height which matches the height of the iframe,
show the hidden div ($("#products_container").slideDown()).
And this all works fine.
And then if you close that product, the iframe is removed and the original page contents come back. All is perfect!
And then if you open a second iframe, it has a height of 0. (This works fine in Chromium; but in Firefox, second and subsequent iframes always have a height of zero.)
The height of the iframe will depend on its content. They have quite simple HTML and reasonably complicated CSS, with min-heights and lots of padding.
I put sleep(5) at the top of the PHP code which generates the iframe, just to help me to double-check what’s going on. As expected, the console.log('URI: ' + uri) fires immediately, and console.log('src: ' + this.src); console.log('height: ' + infr_height) happens after the five-second delay. This means that the iframe is indeed loaded before we try to calculate the height.
I’ve tried using $(infr).load() instead of infr.onload. That makes no difference. I’ve made sure that the onload event is set before the src is set, and before the iframe is appended to the HTML, to ensure that it is fired correctly. I added $("iframe").remove() when the iframe is closed, to ensure that the previous iframe wasn’t hanging around confusing matters.
Nothing I can think of has any effect.
page_href = document.location.href;
function open_product(uri, hist) {
console.log('URI: ' + uri);console.log('URI: ' + uri);
$('p').slideUp();
$("#products_container").slideUp();
var infr = document.createElement('iframe');
infr.style.border = 'none';
var infr_height;
infr.onload = function() {
var $pc = $("#product_content");
$pc.css('width', '100%');
infr_height = $(this).contents().height();
console.log('src: ' + this.src);
console.log('height: ' + infr_height); // always zero on second and subsequent loads
$(this).css('width', '100%');
$(this).css('height', '100%');
$pc.height(infr_height);
$pc.slideDown();
if (hist) {
var uri = $(this).contents().find('#canonical').attr('href');
// I can't get the state to work the way I want it to, so I'll do this
// with the pathname. Bah!
history.pushState(null, null, uri);
}
var close = document.createElement('img');
close.src = '/custom/public/styles/gallery/fancybox/button_close.png';
close.onclick = close_product;
app.get("product_content").appendChild(close);
close.style.position = 'absolute';
close.style.right = '50px';
close.style.top = '10px';
};
infr.src = uri;
var pc = app.get("product_content");
pc.appendChild(infr);
pc.style.position = 'relative';
}
function show_all_prds() {
var $pc = $("#product_content")
$pc.slideUp();
$("iframe").remove();
$pc.empty();
$pc.attr('style', '');
$('p').slideDown();
$("#products_container").slideDown();
}
function close_product() {
show_all_prds();
history.pushState(null, null, page_href);
}
$("a.inlineframe").click(function(e) {
e.preventDefault();
open_product(this.href, true);
});
window.onpopstate = function(e) {
var uri = document.location.toString().split('/');
var section = uri[3];
if (section === 'products') {
var prd = uri[4];
console.log(prd);
var open = '/custom/api/product.output.php?name=' + prd;
open_product(open, false);
} else {
show_all_prds();
}
};
I'm trying to get width and height of element's background-image. When you click on it, it should show it inside the element ("200 300" in this case).
HTML:
<div id='test'></div>
CSS:
#test {
width: 100px; height: 100px;
background-image: url(http://placehold.it/200x300);
}
JavaScript:
$('#test').on('click', function () {
$(this).text(getDimensions($(this)));
});
var getDimensions = function(item) {
var img = new Image(); //Create new image
img.src = item.css('background-image').replace(/url\(|\)$/ig, ''); //Source = clicked element background-image
return img.width + ' ' + img.height; //Return dimensions
};
Here's the Fiddle. The problem is it works only in Chrome, all the other main browsers return "0 0". I have no idea what's the reason. Isn't that graphic fully loaded?
The issue is that some browsers add quotes to the CSS, and it was trying to load (in the fiddle's case) "http://fiddle.jshell.net/_display/%22http://placehold.it/200x300%22". I've updated your .replace() to look for " as well, and a fiddle is at http://jsfiddle.net/4uMEq/
$('#test').on('click', function () {
$(this).text(getDimensions($(this)));
});
var getDimensions = function (item) {
var img = new Image();
img.src = item.css('background-image').replace(/url\(|\)$|"/ig, '');
return img.width + ' ' + img.height;
};
I guess you need to wait for onload event on image.
So I am creating a new image element once I get response from AJAX call with image metadata like this:
var loadedImageContainter = $('<div class="loaded-image-container"></div>');
var image = $('<img src="' + file.url + '" alt="">');
loadedImageContainter.append(image);
$('.loading-image').replaceWith(loadedImageContainter);
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
But width() and height() functions are returning 0 although image has 30 x 30 px size and it appears correctly on the page. I need to get its dimensions in order to absolutely position the image.
You need to wait until the image has loaded to have access to the width and height data.
var $img = $('<img>');
$img.on('load', function(){
console.log($(this).width());
});
$img.attr('src', file.url);
Or with plain JS:
var img = document.createElement('img');
img.onload = function(){
console.log(this.width);
}
img.src = file.url;
Also, you don't need to insert the image into the DOM before you read the width and height values, so you could leave your .loading-image replacement until after you calculate all of the correct positions.
That is because your image isn't loaded when you check width
Try using load event this way
$('img').on('load',function(){
// check width
});
You can also use the alternate API $.load method:
$('<img src="' + file.url + '" alt="">').load( function(){ <your function implementation> });
As #ahren said earlier the reason is that image not loaded when you tring to get it's sizes.
If you want to fix this without jQuery you can use vanilla JS addEventListener method:
document.getElementsByTagName('img')[0].addEventListener('load', function() {
// ...
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
// ...
});
For me it only works with "appendTo"
$('<img src="myImage.jpeg">').load(function(){
$w = $(this).width();
$h = $(this).height();
$(this).remove()
}).appendTo("body")
Try this:
$('.loading-image').replaceWith(loadedImageContainter);
$('.loading-image').load(function(){
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
});
If you put it inside the AJAX call, that will work too, this is for json method
$.post("URL",{someVar:someVar},function(data){
var totalImgs = $('body').find('img').length;
var image = $('<img src="' + data.file[0].url + '" alt="" id="IMG_'+ totalImgs +'">');
loadedImageContainter.append(image);
$('.loading-image').replaceWith(loadedImageContainter);
var width = $('#IMG_'+totalImgs).width();
var height = $('#IMG_'+totalImgs).height();
},'json');
This doesn't seem to be working for me. I want to perform these actions only on images with a title attribute set. It seems my problem is when I use $(this), it is referring to the title attribute? Thanks in advance.
(function($) {
$(function() {
/* Run this only if images have a title attribute */
if ($('.node-page img[title], .node-news img[title]')) {
$(this).each(function() {
var image = $(this);
var caption = image.attr('title');
var imagealign = image.css('float');
image.after('<span class="caption">' + caption + '</span>');
image.next('span.caption').andSelf().wrapAll('<div>');
image.parent('div').addClass('caption-wrapper').css({'width': imagewidth, 'height': 'auto', 'float': imagealign});
});
}
});
})(jQuery);
It seems you got mixed-up with the if and the each(). You should apply your each to your selector directly. If no image have a title attribute then it won't do anything, else it will apply your function to each element.
(function($) {
$(function() {
/* Run this only on images that have a title attribute */
$('.node-page img[title], .node-news img[title]').each(function() {
var image = $(this);
var caption = image.attr('title');
var imagealign = image.css('float');
image.after('<span class="caption">' + caption + '</span>');
image.next('span.caption').andSelf().wrapAll('<div>');
image.parent('div').addClass('caption-wrapper').css({'width': imagewidth, 'height': 'auto', 'float': imagealign});
});
});
})(jQuery);