is possible to get background image width which is defined in CSS?
body {
background-image: url('background.jpg');
}
I need something like this:
window.getComputedStyle(document.body, 'background-width');
var u = window.getComputedStyle(document.body, 'background-image');
u = u.replace(/url\(/, '').replace(/\)/, '');
var w = 0;
var i = new Image();
i.onload = function( ){ w = this.width; alert(w); }
i.src = u;
warning: i have ommitted a case, when body has no background image specified, keep that in mind.
is possible to get background image width which is defined in CSS?
I don't think so, but you should be able to use a little trick : Load the image into an img element as described in this question.
If you do this after the document has been fully loaded, the browser should fetch the image from the cache.
It's impossible to do this directly without some sort of work around.
Use JQuery to detect what image the background has, with the imagesLoaded (recommended) or onImagesLoad plugin.
Use the JQuery Dimensions plugin to get the image size.
Related
UPDATE:
I just found some more info. It seems that in Chrome, the currentSrc of the image will often be empty, whereas in Firefox, the URL is always correct. Is the JS trying to access currentSrc before it's available? Is there a way to prevent this?
I am creating a Drupal 8 website, and in order to use the responsive images module with a background-image, I came up with the following workaround. The JS function below, setParallaxImage(), takes the currentSrc from the img in the picture element and sets it as the background-image for the outermost div. The img itself is not displayed (display: none in CSS) and is given a dummy image, as I only need it to get the currentSrc. The function is called with onload and onresize.
The code seems to work well in Firefox. When resizing the browser past a breakpoint, the image goes grey for a split second, then loads the image from the proper source. However, with Chrome, when quickly resizing past a breakpoint, the image may become grey and not get displayed at all, that is, background-image: url(). Usually if I resize the window a couple more times, the image will finally appear. Does anyone know why this might be happening? Thank you for reading.
JS
function setParallaxImage() {
const parallaxContainer = document.getElementsByClassName('paragraph--type--parallax-banner-with-text');
for(var i = 0; i < parallaxContainer.length; i++) {
console.log('in setparallax');
var x = parallaxContainer[i];
var parallax = x.getElementsByClassName('field--name-field-parallax-image-top-')[0];
var picture = parallax.getElementsByTagName("picture")[0];
var sourceURL = picture.querySelector('img').currentSrc;
x.setAttribute('style', 'background-image: url(' + sourceURL +')');
var img = picture.getElementsByTagName("img")[0].setAttribute('src', '/sites/default/files/src_images/dummy_image.gif');
}
}
window.onload = setParallaxImage
window.onresize = setParallaxImage;
HTML
<div class='paragraph--type--parallax-banner-with-text'>
<div class='field--name-field-parallax-image-top-'>
<picture>
<!-- several source tags here -->
<img src="will-be-given-dummy-image-in-JS">
</picture>
</div>
</div>
You can use the property "complete" to check, if the image was already loaded. If not, u can use the onload-Event to fire, when the image is available.
if (img.complete) {
console.log(img.currentSrc);
} else {
img.onload = function() {
console.log(img.currentSrc);
}
}
I have an image source:
var _img = <img src="../images/yadayada.jpg">
And I want it enlarge it or shrink it without cropping it, but I'd rather not grab the element after and change the css.
I tried:
_img.height = 200;
and
_img.style.height = 200
But the first crops it, and the second does nothing.
Style values need units so the style setting would be like this:
_img.style.height = "200px";
This will change the scaled size of the image. If you only set just the height or just the width, then the other should scale to maintain the aspect ratio. You will have to make sure that the HTML layout the image is positioned in is flexible and can handle the image changing size.
Image resize demo: http://jsfiddle.net/jfriend00/K8GJQ/
It's a little hard to tell if you're trying to change an existing image or set dimensions for a new image you're trying to create...
The statement var _img = <img src="../images/yadayada.jpg"> won't do anything by itself except cause your JS to fail to load (it's just a string, and is missing surrounding quotes and semicolon).
If you're trying to target an image that's already in the HTML, give its <img> tag a unique ID that you can target, and then set the width or height.
In the HTML: <img id="yadayadaImage">
In the JS:
var myImage = document.getElementById('yadayadaImage');
myImage.style.width = "200px";
Setting only style.width OR style.height here should keep the image from being cropped, since the other dimension should expand automatically. If it's still cropped check the parent element's width & height attributes, because that may be what's restricting the size.
.
If you're actually trying to create a new image w/specific source and dimensions, what you had above won't work. You need to create a new<img> element with those attributes, then append it to the document.
var targetDiv = document.getElementById("myPhotoDiv");
var imgTag = document.createElement('img');
imgTag.id = "yadayadaImage";
imgTag.className = "uncroppedImage";
imgTag.src = "../images/yadayada.jpeg";
//you COULD set height & width properties here, but that's what CSS is for.
imgTag.style.width = "200px";
targetDiv.appendChild(imgTag); //add the new img to the page
The best approach, but which you said you didn't want to do, is to use CSS and create a class that you can reuse for other images where you don't necessarily know the specific width or height.
.uncroppedImage{
width:100%;
}
Better setup an id for your image like this
<img id="myImg" src="../images/yadayada.jpg">
and use the script below
var myImg = document.getElementById('myImg');
if(myImg && myImg.style) {
myImg.style.height = '200px';
}
In this case, I set an image with width: 100% and height: auto (actual image size is 362x614). I need to get height of image for another step.
Here is my code:
<img class="phone" src="img/phone2.png">
and js:
$(document).ready(function() {
phoneSlider();
});
$(window).resize(function(){
phoneSlider()
});
function phoneSlider(){
var phoneMaskWidth = $(".phone").width();
var phoneMaskHeight = $(".phone").height();
console.log(phoneMaskWidth + "|" + phoneMaskHeight);
.......
}
Then, I check in the console, and the result: 362|0. Why is phoneMaskHeight showing 0 and how can I get the real height?
Move your code from $(document).ready() to $(window).load(). The browser needs to load the image (or at least the image header) before it can calculate its width and height. Document ready event can fire before the browser has chance to have a look at the image.
Demo here; change the image source (or empty browser cache), run and look at the console
use:
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = $(".phone").attr('src');
Working Fiddle
$("img.phone").on('load', function() { alert( this.height ); });
This worked for me.
Browsers load images asynchronously and until the image is fully loaded its height will be unknown.
As others have suggested you will need to attach your code to the "onload" event that is fired when the image is loaded, but that will force you to change your whole phoneSlider method. You will need to put everything that depends on the height of the image in the corresponding onload callback.
If you don't need to do your calculation as soon as the image is loaded, the Salman A's answer is the better approach - put your logic when the window#onload event is fired, this ensures all external resources (including images) are loaded.
$(document).ready(function(){
console.log($('#myimg').width() + 'x' + $('#myimg').height());
console.log($("#myimg").attr('src'));
})
working demo [http://jsfiddle.net/A5QJM/238/]
This is really for informational and learning purposes while learning more about JavaScript and CSS. I have a local browser index page that I wanted to rotate the background image onload. After looking around and playing with different solutions, I settled on this for the basic rotate functionality:
<html>
<head>
<script language="javascript" type="text/javascript">
function rotate()
{
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var img = imgArray[aImg];
document.body.style.background = "url(" + img + ") no-repeat";
document.body.style.backgroundSize = "cover";
}
</script>
</head>
<body onload="rotate()">
</body>
</html>
During the process, before I just set the backgroundSizeas cover to fill the window, I was playing with the idea of resizing the images before setting them as the background image after they are selected from the array.
I have done a lot of searching, and the only real working solutions I have found rely on selecting the element by ID, but that also requires that the image has an ID associated, such as in the IMG property in the HTML code. Here the image is selected and set in the JavaScript with CSS.
I have tried setting the image dimensions with img.width / img.height and img.style.width / img.style.height, as well as a few other random solutions I have come across, but whenever I try to change these the image either does not change or it does not show at all.
function rotate()
{
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var img = imgArray[aImg];
image = rsize(img);
document.body.style.background = "url(" + image + ") no-repeat";
document.body.style.backgroundSize = "cover";
}
function rsize(image)
{
image.style.width = "300px";
image.style.height = "300px";
return image;
}
I know I am probably doing something wrong here. Is there a way, in this circumstance, that I can resize these images? Or is there a better way to construct this?
Thanks in advance.
You must set image.style.width and image.style.height on an actual image DOM object, not on the URL as you are currently trying to do.
As an image object is not used for background images, you can't really directly do what you're trying to do for a background image.
You could use the CSS background-size property, but that is fairly new and is not supported in versions of IE prior to IE9. If you were using that, you would set the actual size for that, not "cover".
You could also use an actual DOM image and then present that DOM image as centered in your page if that's what you're really trying to do.
For example, here's how you create a DOM image object, assign it a URL, set it's size and insert it into your page:
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var imgURL = imgArray[aImg];
var img = new Image();
img.src = imgURL;
img.style.width = "300px";
img.style.height = "300px";
img.id = "centeredImage";
document.body.appendChild(img);
You could then use CSS to position is in the center of your page if you wanted.
Working demo here: http://jsfiddle.net/jfriend00/jqMtV/
No, you have no <img> elements you could (re)size (btw, they would not need ids to be selectable). Your use of rsize(imgArray[aImg]) operates on the array members, which are strings and not DOM elements, so setting values on their non-existent style property would throw an error.
Yet, you're already on the right way with using the backgroundSize style property. Just don't set it to cover, but to the size you need!
document.body.style.backgroundSize = "300px 300px";
If you would want to use a <img> element, add this at the end of your <body>:
<img src="some.jpg" style="position:fixed; z-index:-1; width:100%; height:100%" />
Currently i am trying to get remote image width/height. I am developing a link sharing module something like when you paste a link on facebook, you can see title, description and images.
So i tried using php getimagesize to get image width/height its very slow.
So i am thinking of using jquery solution to get remote image width/height so that i can filter image width less then 100px.
I am new in jquery/javascript
I tried something like
var img = $('#imageID');
var width = img.clientWidth;
var height = img.clientHeight;
$('#info').html(width+'.. height: '+height);
Its not working and return undefined .. height: undefined
Any help is appreciated.
Thank you
Try this:
var img = new Image();
img.src = 'http://your.url.here/image.png';
img.onload = function() {
$('#info').text('height: ' + img.height + ' width: ' + img.width);
};
This approach would let you get the image info without having to have an <img> tag at all. Now, perhaps you want the image to be on the page, so you'd do what #patrick suggests in that case.
If you're trying to get the width and height of the image in the client side, you can use jQuery's .width() and .height() methods.
Example: http://jsfiddle.net/aeBWQ/
$(window).load(function() {
var img = $('#imageID');
var width = img.width();
var height = img.height();
$('#info').html(width+'.. height: '+height);
});
Doing $(window).load() will ensure that the images are loaded before getting the height/width.