Getting true dimensions of images with jquery on collected dom elements - javascript

I am trying to get the dimensions of images on a page for further use with a custom 'lightbox' or sorts. However, when trying both a pure js method, and a jquery method, I get the output undefined on my variables. Why is this? Is it because of jquery load event? I tried both onload and ready.
Basically I need the full dimensions of the image to justify whether it should be loaded in a lightbox with a click event or not.
Update I am now able to get console feedback from the function now, however it's not providing me a dimension of the image.
$('.postbody').find('img').each(function() {
var img = new Image(), width, height;
$(img).load(function() {
width = $(this).width();
height = $(this).height();
console.log('Width: '+width+' Height: '+height);
});
console.log($(this).attr('src'));
img.src = $(this).attr('src');
});
#theater-box {
display: none;
position: fixed;
width: auto;
height: auto;
min-width: 1005px;
max-width: 1428px;
padding: 10px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,0.90);
border: 2px solid rgba(255,255,255,0.4);
}
.postbody {
width: 90%;
height: 90%;
background: rgba(100,50,50,0.5);
}
.postbody * img {
width: 100%;
max-width: 1168px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="theater-box"></div>
<div class="postbody">
<div id="someclass"><img src="https://e8zzxa.bl3301.livefilestore.com/storageservice/passport/auth.aspx?sru=https:%2f%2fe8zzxa.bl3301.livefilestore.com%2fy2pDapooeiISgUV7-ugpyADuRULJ_stpkiALbypYJHjNxrhUqcvRsZ6eRk4PiJlClABLOfByjulDSDLOMCEpHhggVkgvM4z5Gdq0Jo-C0e1pCU%2fMajipoorHighlands2.jpg&wa=wsignin1.0" /></div>
</div>

You are setting the variables asynchronously and getting it directly.
In pseudocode it is a bit like this:
Set the function to retrieve the width and height when the images loads
Display the width and height variables (not set yet)
The functions set in step 1 runs and sets the varaibles.
So your code that uses the width and height should be inside the image.load function.
I hope it helps, if you have any further questions dont hesitate to comment :-)

Perhaps you can just put the console.log line as the last line in the $(img).load function.

Try this...
$(img).load = function() {
var $this = $(this);
width = $this.width();
height = $this.height();
}

I'm not exactly sure why the original method (which works in a lot of examples) was not working here. So I found some awesome code by GregL from right here at Stackoverflow.
Essentially, the method loads a new, and hidden image into the body, and then captures the width and height before removing it.
$('.postbody').find('img').each(function() {
var img = $(this), width, height,
hiddenImg = img.clone().css('visibility', 'hidden').removeAttr('height').removeAttr('width').appendTo('body');
width = hiddenImg.height();
height = hiddenImg.width();
hiddenImg.remove();
console.log('Width: '+width+' Height: '+height);
});
Check out the Fiddle

Related

An image with width larger than the window size initially loads as the same width as the window

What I am trying to do is center an image using this bit of jQuery. The selector for my image is " .section-header img ".
var image_center = function(){
var imageWidth = $('.section-header img').width();
var windowWidth = $(window).width();
var centerFix = -(imageWidth-windowWidth)/2 ;
console.log(imageWidth, windowWidth, centerFix);
$('.section-header img').css({'left': centerFix});
}
I call the function when the document is ready and when the window is resized:
$(document).ready(function(){
image_center();
$(window)resize(function(){
image_center();
}
My problem is that I cannot get the function to work when the window initially loads. Looking in my console, the browser reads the image as having the same width as the browser. Once I resize the browser, the actual width of the image is read. Is there something built into Chrome that is tripping me up here? Is there an easier way to do this (without using background-image)??
Thank you,
CPR
It would probably be easier to use css for this job.
.section-header {
background-image: url("/path/to/image.jpg");
background-position: center;
background-size: contain;
background-repeat: no-repeat;
}
Not sure if you also want the img to resize.
Here is an example with resize and your img tag + section-header div or whatever it is:
.section-header{
width: 50%;
left: 25%;
margin-left: auto;
position: absolute;
}
img{
width: 100%;
height: 100%;
}
<div class="section-header">
<img src="http://placehold.it/350x150" alt="">
</div>
https://jsfiddle.net/Lj4mfqLa/
UPDATE:
You could also try to wrap your jquery code in:
$(window).load(function(){
//initialize after images are loaded
});
instead of
$(document).ready(function(){})

Adjusting a div based on the size of the container

I have an HTML video player with Javascript generated controls(with background images of SVG graphics). I'm having an issue using the css calc() function, and need to resize the div's based on the video controls bar. So when the window is expanded/contracted, the controls need to adjust accordingly.
The controls div:
//Controls Wrapper
videoObj.controlsWrapper = document.createElement("div");
videoObj.controlsWrapper.className = "video-controls";
The controls are generated dynamically, so for instance, the play button is generated by this:
videoObj.playBtn = document.createElement("button");
videoObj.playBtn.className = "play btn";
So the question is how to adjust the size of the play button(which is a background of an SVG graphic), to a percentage(about 25%) of the height of the controls wrapper div.
jsfiddle
This is the easiest way... try resizing the box :)
The parent is relative. The child is absolute. Setting the top, left, right and bottom all to 0 will actually create a spider web effect ( or stretch effect ). I used different pixels so you could see the reaction. otherwise the child will cover the parent. Hope this helps.
http://jsfiddle.net/m5wm1rLs/
.parent{
position: relative;
width: 100px;
height: 100px;
background-color: red;
}
.child{
position: absolute;
top: 3px;
bottom: 20px;
left: 3px;
right: 20px;
background-color: green;
}
<div class="parent">
<div class="child"></div>
</div>
To test that this works, you can make parent resizable:
$('.parent').resizable();
Resizing it to 25% of the parent div height is relatively easy, but only doable with a scripting language. As far as CSS has come by allow calc(), it has no support for pulling the sizes of designated elements.
Here's a simple script I threw together for you:
window.onload = function() {
resize();
}
window.onresize = function() {
resize();
}
function resize() {
document.getElementsByClassName('play')[0].style.width = (document.getElementsByClassName('timeline')[0].offsetHeight * .25) + 'px';
}
JSFiddle: http://jsfiddle.net/zq2vzkk5/
I recommend you use ids to identify the elements you want to pull the values from, but if the positions of the elements won't change on the page, then classes are fine. You just have to update which instance of the class you want to pull the value from if it does change.
If you want a jQuery variation, I can supply that, too.
I hope this helps.
Edit:
Here's the jQuery variation:
$(function() {
resize();
$(window).resize(function() {
resize();
});
});
function resize() {
$('.play').first().width($('.timeline').first().outerHeight() * .25);
}
JSFiddle: http://jsfiddle.net/s51vrca2/
You can do this without JS :
.play {
height: 25%;
}

Changing the mask height depending on a responsive image

Having a problem in trying to copy the height of a responsive image to my mask on first load and on every time the window is resized. I've tried a few js scripts, but still I cant make it happen.
It is really a responsive image slider with a div(mask) exactly over it whatever the viewport screen size is.
this is my jQuery script:
function maskInit(){
var offsetDots = $("#slide").offset().top + $("#slide").height() + "px";
$("#mask").height() = offsetDots;
}
$(document).ready(function() {
maskInit();
});
$(window).resize(function(){
maskInit();
});
and my CSS:
#slide{
height: 10vw; /* to simulate a responsive image */
width: 100%;
margin: 0;
padding: 0;
background: red;
z-index: 0;
}
#mask{
position: absolute;
z-index: 1;
top: 0;
right: 0;
left: 0;
background: gray;
opacity: 0.8;
}
I've setup a jsFiddle here to simulate my problem
There is something wrong with your script.
You are NOT setting the mask height with this:
$("#mask").height() = offsetDots;
Check jQuery .height()
Instead use it this way:
$("#mask").height(offsetDots);
or you can set via css:
$("#mask").css({"height":offsetDots});
Here's your updated jsFIDDLE demo
.height() is a function so you can not do $("#mask").height() = offsetDots; use $("#mask").height(offsetDots); or by .css({"height":offsetDots}) to set height.

How to resize a div to clients viewport height?

Ok, so i want to have a series of divs which are the exact width and height of the user's browser window, regardless of the screen size. I can easily make the divs stretch horizontally with "width: 100%;" but i cant work out how to make the height stretch itself. I am guessing that i need to use some bit of javascript to judge the height, and then another piece to resize the seperate divs. Unfortunately I am a complete javascript n00b and after two hours of seemingly fruitless searching and coming up with about 100 "solutions" this was as far as id gotten (Im sure that at some point I have probably been closer to the answer):
var viewportHeight = "height:" + document.documentElement.clientHeight;
getElementById('section-1').setAttribute('style', viewportHeight);
<div class="section" id="section-1"></div>
<div class="section" id="section-2"></div>
<div class="section" id="section-3"></div>
edit:
ah i should be more clear, im attempting to have all three divs take up the entire screen, so you have to scroll down to see each one - almost like seperate slides. The idea is that each one takes up the entire screen so you cant see the next section until you scroll down, rather than having three divs which take up a third of the screen.
If you haven't already tried it, you'll want to look at parent:child inheritance of elements within the DOM by way of using CSS.
What I want to STRESS is that everyone giving you JS hacks to accomplish this is not only providing you with overkill (YOU did ask for a JavaScript solution, so they gave it to you!), but it's also a deviation from standards. HTML is for structure, CSS is for presentation, and JavaScript is for behavioral aspects... setting a div to the width of the viewport on load is a PRESENTATION aspect and should be done in CSS... not JavaScript. If you were trying to change the width based on events or user interaction, then yes JavaScript is your friend... but stick with just HTML and CSS for now.
The trick is that most elements have an undefined height - and height is later defined by the content that the element holds.
If you want to 'trick' an element into having a height other than what it wants to default to, you'll have to explicitly define it. Since you want to inherit your height from the viewport, you'll have to define the height at the top and bring it down...
You might be in luck and can avoid JavaScript altogether (unnecessary). Just use CSS.
Try something like:
html, body {
height: 100%;
width: 100%;
}
Now, when you try to set your div's later on, specify width: 100% and the height gets inherited from the html --> body --> div.
Try that and see if that solves your problem - if not, point us to a website, a pastebin, or a SOMETHING with code in it that we can just show you how to do it (whereas what you posted for code was an attempt in JavaScript which is only 1 part of the code - post the full thing either to a server or temp site like pastebin).
Here is some sample code I wrote (tested in Chromium):
The HTML:
<html>
<head>
<title>Test Divs at 100%</title>
<link rel="stylesheet" type="text/css" href="divtest.css"
</head>
<body>
<div class="test1">aef</div>
<div class="test2">aef</div>
<div class="test3">aef</div>
</body>
</html>
The CSS:
html, body {
width: 100%;
height: 100%;
background-color: #793434;
padding: 0;
margin: 0;
}
div {
height: 100%;
width: 100%;
}
.test1 {
background-color: #E3C42E;
}
.test2 {
background-color: #B42626;
}
.test3 {
background-color: #19D443
}
try this
div#welcome {
height: 100vh;
background: black;
color: white;
}
div#projects {
height: 100vh;
background: yellow;
}
<div id="welcome">
your content on screen 1
</div>
<div id="projects">
your content on screen 2
</div>
it should work for you, but little support in IE
A bit of jQuery should do it:
$(document).ready(function() {
var window_height = $(window).height();
$('#section-1").height(window_height);
});
And if you want to keep 100% height on window resize:
$(document).ready(function() {
function viewport_height() {
var window_height = $(window).height();
$('#section-1").height(window_height);
}
viewport_height();
$(window).resize(function() {
viewport_height();
});
});
try this
window.onload = init;
function init()
{
var viewportHeight = "height:" + document.documentElement.clientHeight+"px;";
document.getElementById('section-1').setAttribute('style', viewportHeight);
}
Here is a script free solution, just CSS. This assumes that the divs are directly in the body element or a parent with position absolute and the parent has no padding.
#section-1 {
position: absolute;
height: 100%;
width: 100%;
background: #ff0000;
}
#section-2 {
position: absolute;
width: 100%;
top: 100%;
height: 100%;
background: #00ff00;
}
#section-3 {
position: absolute;
width: 100%;
top: 200%;
height: 100%;
background: #0000ff;
}
See fiddle: http://jsfiddle.net/QtvU5/1/

Zoom on a picture on resizing

I'm developing a website where I have to display a picture (not a problem).
But, I have to display it as this link: http://buildinternet.com/project/supersized/slideshow/3.2/demo.html
So, On resizing, I have to zoom on the picture to never scale it.
Does some on know how to do it?
Here is what I have:
html:
<div id="container_images">
<ul>
<li><img src="images/desktop/myimage.jpg" alt="An awesome image"></li>
</ul>
</div>
CSS:
#container_images{
display: block;
position: fixed;
left: 0;
top: 0;
overflow: hidden;
z-index: -999;
height: 100%;
width: 100%;
}
#container_images li{
display: block;
list-style: none;
z-index: -30;
position: fixed;
overflow: hidden;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity:1;
}
#container_images li img{
width: 100%;
height: 100%;
display: block;
}
If I understood correctly you don't need the browser's inbuilt zooming (ctrl+), you just want to make the picture fill in the whole window of the browser when the window is resized.
You will need 2 things for that.
First, you need some javascript to execute on window resize event, then you will need some simple maths to calculate the center of the picture taking into account the new window size and set left/top margin of the picture to new values.
You can easily do that with jQuery:
$(window).resize(function() {
var h = $(window).height();
var w = $(window).width();
var pic = $('#container_images img');
var pic_width = pic.width(), pic_height = pic.height();
$(pic).css('margin-left': (w - pic_width)/2).css('margin-top': (h - pic_height)/2);
});
One thing to remember is that if your picture's width/height is already changed from its original size, you will get that new size from width() and height() functions.
So you either should make sure the original is not touched, or use one of the solution out there for grabbing the original picture size (e.g. How do I get actual image width and height using jQuery?).
Also the above snippet is to just get you started, you should grab the picture and its parameters in some init function and only recalculate/modify css on resize event.

Categories