tags:

views:

391

answers:

4

Hi guys, as the title said i am trying to use php to get the height of a < div> element then with that value, applying to an image. This would actually shrink the image or stretch the image. As i am still new to coding, i searched online and what i found is only solution of doing it in javascript, which is something like this

DivHeight = document.getElementById("TheDiv").offsetHeight

but i couldn't find any that uses php to do so.

A: 

You can't get the div's height in PHP, as when the page is rendered and the div is displayed, PHP has already gone away. The only way to do that is to get the height with javascript, then get the image via AJAX.

You know, you can shrink the image with only javascript by changing the width and height of the image. The results are not optimal, but it will probably work just fine for your purposes.

Tatu Ulmanen
+2  A: 

php is a server side language, which you cannot get the height of a div.

you may specify the image size by adding attributes

joetsuihk
A: 

As others here said, you can't do this with PHP. But why not just use CSS?

If the containing DIV has a height and width, you can set the image style to fill that space (stretching or shrinking in the process) with:

.imgclass {
  height: 100%
  width: 100%
}

However, if you want to actually resize the images physically on the server, then you have to use AJAX and request the new image via Javascript (which may be slow, depending on how long it'd take your server to generate them).

I would recommend against the latter, unless you pre-build a bunch of sizes and use the one that matches closest and then resize it in the browser with CSS.

Artem Russakovskii
A: 

As mentioned, 'client side' code has to do this, as HTML (divs, images etc - the stuff you are trying to manipulate) is rendered on the client side. That means javascript. I recommend using the jquery library - the following line should do it:

$('#theImagesId').css({width: $('#theDivsId').height()+"px"});

However, what you are trying to do sounds a little odd? Also bare in mind that the returned height may be smaller than it should, if there is already an image or something loading in the div. This is because the javascript will execute once the DOM has loaded (so, all the actual html code), but not necessarily the images within it.

Tom Bates