get jquery image width and add class - php

I'm having trouble getting the dimensions of a series of images that are loading via PHP.
<?
$Ldir="imgs/liveGallery/"; // Directory where files are stored
if ($Lhandle = opendir($Ldir)) {
while (false !== ($Lfile = readdir($Lhandle))) {
if ($Lfile != "." && $Lfile != "..") $Lthefiles[] = $Lfile;
}
closedir($Lhandle);
}
sort($Lthefiles);
for ($Li=0;$Li<count($Lthefiles);$Li++) { ?>
<a href="<?php echo $Ldir.$Lthefiles[$Li]; ?>" class="ilightbox">
<div class="adj">
<img src="<?php echo $Ldir.$Lthefiles[$Li]; ?>" class="percent">
</div>
</a>
<?php }
?>
In the above code PHP is doing its job loading all the images from a nearby directory. The .adj class is formatting the <div> into a square and floating them all to the left so they tile the screen. It's also hiding the overflow so that no matter the dimensions all you see is a square.
My issue comes when trying to read the widths and heights of the images that are being loaded into that <div>. I want to have the image fit at a width or height of 100% depending on which is proportional to fill the square. Here's the jquery code I thought should work.
$(window).load(function() {
$(".adj").each(function() {
var $this = $(this);
var imageWidth = $this.children("img").attr("width");
var imageHeight = $this.children("img").attr("height");
if (imageWidth < imageHeight){
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
});
});
I don't seem to be capturing an image width or height at all, with what I wrote above.
I'm using fullpage.js and ilightbox.js which may be messing with my code, but I doubt it. I've also tried putting a modified version of this code inside the PHP for loop (without the jquery each function) and that doesn't work either. HELP!
Here's a link for you.

You can try somethig like
$(window).load(function() {
$(".adj").each(function () {
var $this = $(this);
var img = new Image();
//Set Image source
img.src = $this.children("img").attr("src");
//Wait for image to be loaded.
//Event will fire when image is loaded
img.onload = function () {
//Get Height and width
var imageWidth = img.width;
var imageHeight = img.height;
if (imageWidth < imageHeight) {
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
};
});
});
Note: I am not sure, this is a best practice

You have set the width and height in the css styling and not inline as attributes,
So attributes width and height are empty
$this.children("img").attr("width"); // .attr would not work
Should be
$this.children("img").css("width"); // .css is the method
And
$(window).load(function() {
$(".adj").each(function() {
var $this = $(this);
// when your referring same img multiple times, grab it in a variable
var image = $this.children("img");
var imgWidth = image.width(); // or image.css("width")
var imageHeight = image.height(); // or image.css("height")
if (imageWidth < imageHeight){
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
});
});
note .css() gives in the px'.
Example 100px even though you set the values in pt or em etc. After seeing your code since your comparing the values I would suggest .width() and .height() as they return integer values and easy to compare
jQuery documentation
Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "width" ) rather than .width()

Related

Upload image after choosing filter

he i have here a script where users can choose a filder, but how can i make it when they are done with choosing a filder that the script sends the picture to a php script so that i can upload on the server?
$(function() {
/*
In this code, we are going to do the following:
1. Accept an image on drag and drop
2. Create a new canvas element (original), with a max size
of 500x500px (customizable) and keep it in memory
3. Listen for clicks on the filters. When one is selected:
3.1 Create a clone of the original canvas
3.2 Remove any canvas elements currently on the page
3.3 Append the clone to the #photo div
3.4 If the selected filter is different from the "Normal"
one, call the Caman library. Otherwise do nothing.
3.5 Mark the selected filter with the "active" class
4. Trigger the "Normal" filter
*/
var maxWidth = 500,
maxHeight = 500,
photo = $('#photo'),
originalCanvas = null,
filters = $('#filters li a'),
filterContainer = $('#filterContainer');
// Use the fileReader plugin to listen for
// file drag and drop on the photo div:
photo.fileReaderJS({
on:{
load: function(e, file){
// An image has been dropped.
var img = $('<img>').appendTo(photo),
imgWidth, newWidth,
imgHeight, newHeight,
ratio;
// Remove canvas elements left on the page
// from previous image drag/drops.
photo.find('canvas').remove();
filters.removeClass('active');
// When the image is loaded successfully,
// we can find out its width/height:
img.load(function() {
imgWidth = this.width;
imgHeight = this.height;
// Calculate the new image dimensions, so they fit
// inside the maxWidth x maxHeight bounding box
if (imgWidth >= maxWidth || imgHeight >= maxHeight) {
// The image is too large,
// resize it to fit a 500x500 square!
if (imgWidth > imgHeight) {
// Wide
ratio = imgWidth / maxWidth;
newWidth = maxWidth;
newHeight = imgHeight / ratio;
} else {
// Tall or square
ratio = imgHeight / maxHeight;
newHeight = maxHeight;
newWidth = imgWidth / ratio;
}
} else {
newHeight = imgHeight;
newWidth = imgWidth;
}
// Create the original canvas.
originalCanvas = $('<canvas>');
var originalContext = originalCanvas[0].getContext('2d');
// Set the attributes for centering the canvas
originalCanvas.attr({
width: newWidth,
height: newHeight
}).css({
marginTop: -newHeight/2,
marginLeft: -newWidth/2
});
// Draw the dropped image to the canvas
// with the new dimensions
originalContext.drawImage(this, 0, 0, newWidth, newHeight);
// We don't need this any more
img.remove();
filterContainer.fadeIn();
// Trigger the default "normal" filter
filters.first().click();
});
// Set the src of the img, which will
// trigger the load event when done:
img.attr('src', e.target.result);
},
beforestart: function(file){
// Accept only images.
// Returning false will reject the file.
return /^image/.test(file.type);
}
}
});
// Listen for clicks on the filters
filters.click(function(e){
e.preventDefault();
var f = $(this);
if(f.is('.active')){
// Apply filters only once
return false;
}
filters.removeClass('active');
f.addClass('active');
// Clone the canvas
var clone = originalCanvas.clone();
// Clone the image stored in the canvas as well
clone[0].getContext('2d').drawImage(originalCanvas[0],0,0);
// Add the clone to the page and trigger
// the Caman library on it
photo.find('canvas').remove().end().append(clone);
var effect = $.trim(f[0].id);
Caman(clone[0], function () {
// If such an effect exists, use it:
if( effect in this){
this[effect]();
this.render();
// Show the download button
showDownload(clone[0]);
}
else{
hideDownload();
}
});
});
// Use the mousewheel plugin to scroll
// scroll the div more intuitively
filterContainer.find('ul').on('mousewheel',function(e, delta){
this.scrollLeft -= (delta * 50);
e.preventDefault();
});
var downloadImage = $('a.downloadImage');
function showDownload(canvas){
downloadImage.off('click').click(function(){
// When the download link is clicked, get the
// DataURL of the image and set it as href:
var url = canvas.toDataURL("image/png;base64;");
downloadImage.attr('href', url);
}).fadeIn();
}
function hideDownload(){
downloadImage.fadeOut();
}
});
Try this...
HTML5 Drag and Drop Uploader - http://demo.tutorialzine.com/2011/09/html5-file-upload-jquery-php/

Gif image only resizes after fully loaded

Gif will only resize after the gif is fully loaded. How do I make the gif resized whilst even loading?
I use multiple gifs so they come in different sizes so I can not just do the usual 100% height and width, I want to keep the aspects correct.
The script I use to resize the gif
<script>
function resizeToMax(id){
myImage = new Image()
var img = document.getElementById(id);
myImage.src = img.src;
if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){
img.style.width = "100%";
} else {
img.style.height = "100%";
}
}
</script>
The php to display the image
<?php
echo '<img id="image" onload="resizeToMax(this.id)" src="gifs/' . $myTokens[1] . '/' . $myTokens[2] . '.gif">';
?>
One thing you may be able to do is have the image hidden until it is loaded (add a CSS class for example), and then in your resizeToMax function, remove the CSS class that is hiding the image.
The onload events fire only when image has finished loading.
In the meanwhile, you could play with the css width and / or height properties, or even max-width and max-height.
The risk is that you don't know the image proportions yet, so the image may looks distorted ehile loading.
IMHO the best solution is to replace the image with a placeholder, load the image without displaying it (eg. outside of the screen window), then resizing and displaying it in the correct position removing the placeholder.
Use window.onload event to make sure your resizing will be effective at beginning of window loading.
<script>
window.onload = function() {
resizeToMax("image");
};
function resizeToMax(id){
myImage = new Image()
var img = document.getElementById(id);
myImage.src = img.src;
if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){
img.style.width = "100%";
} else {
img.style.height = "100%";
}
document.getElementById(id).style.display = "block";
}
</script>
<?php
echo '<img id="image" style="display:none;" src="gifs/' . $myTokens[1] . '/' . $myTokens[2] . '.gif">';
?>
Or hide your image in css and show it in your function after your resizing.

Jquery overlay from checking php variable

I have this script from JQuery.
<script>
// create custom animation algorithm for jQuery called "drop"
$.easing.drop = function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
};
// loading animation
$.tools.overlay.addEffect("drop", function(css, done) {
// use Overlay API to gain access to crucial elements
var conf = this.getConf(),
overlay = this.getOverlay();
// determine initial position for the overlay
if (conf.fixed) {
css.position = 'fixed';
} else {
css.top += $(window).scrollTop();
css.left += $(window).scrollLeft();
css.position = 'absolute';
}
// position the overlay and show it
overlay.css(css).show();
// begin animating with our custom easing
overlay.animate({ top: '+=55', opacity: 1, width: '+=20'}, 400, 'drop', done);
/* closing animation */
}, function(done) {
this.getOverlay().animate({top:'-=55', opacity:0, width:'-=20'}, 300, 'drop', function() {
$(this).hide();
done.call();
});
}
);
$("img[rel]").overlay({
effect: 'drop',
mask: '#789'
});
</script>
Right now it works by me clicking on an image. Then the overlay comes up with whatever is in the div. However I want to take out clicking the image and just have the overlay come up with an if statement in PHP. any ideas...im not very good at js.
EDIT:
yes im using the JQuery plugin Easing. However the overlay works great...and the overlay works by clicking on an image with the rel attribute like this
<img src="http://farm4.static.flickr.com/3651/3445879840_7ca4b491e9_m.jpg" rel="#mies1"/>
However I don't want to click on the images I want it to come up automatically.
<?php if ($whatever) { ?>
$(document).ready(function() {
$("img[rel]").click();
});
<?php } ?>

Jquery Fast image switching

I have a php class that generates a map image depending on my db data. It is periodically updated thru a serInterval loop.
I am trying to update it with no flickering but I just can't. I've tried different methods (preloader, imageswitcher) with no success.
//first load
function map() {
$("#map").html("<img src=map.php?randval="+Math.random()+">");
}
//update it from setInterval calls
function updatemap() {
$("#map").fadeOut(function() {
$(this).load(function() { $(this).fadeIn(); });
$(this).attr("src", "map.php?randval="+Math.random());
})
}
Is there any way to update the image with no flickering at all? I would prefer an inmediate swap insteado of a fade.
The problem I'm having is that after calling updatemap() the image just dissapears. ¿Maybe it is a problem with the attribute src I am parsing?
THanks for your help.
You may still get a very slight flicker.
function updatemap() {
var img = new Image();
img.onload = function(){
$("#map img").attr("src", img.src);
}
img.src = "map.php?randval="+Math.random();
}
You need to load the subsequent maps into a hidden element first. Then when they're loaded, swap them in.
<div id = "map"></div>
<img id = "load-map" src = "" alt = "" />
$(document).ready(function(){
$("#map").html("<img src=map.php?randval="+Math.random()+">");
setTimeout(loadImage,5000);
}
function loadImage()
{
$("#load-map")
.attr('src','map.php?randVal='+Math.random())
.load(function(){
$("#map img").src($("#load-map").src);
setTimeOut(loadImage,5000);
});
}

Resize iframe height according to content height in it

I am opening my blog page in my website. The problem is I can give a width to an iframe but the height should be dynamic so that there is no scrollbar in the iframe, and it looks like a single page...
I have tried various JavaScript code to calculate the height of the content but all of them give an access denied permission error and is of no use.
<iframe src="http://bagtheplanet.blogspot.com/" name="ifrm" id="ifrm" width="1024px" ></iframe>
Can we use Ajax to calculate height or maybe using PHP?
To directly answer your two subquestions: No, you cannot do this with Ajax, nor can you calculate it with PHP.
What I have done in the past is use a trigger from the iframe'd page in window.onload (NOT domready, as it can take a while for images to load) to pass the page's body height to the parent.
<body onload='parent.resizeIframe(document.body.scrollHeight)'>
Then the parent.resizeIframe looks like this:
function resizeIframe(newHeight)
{
document.getElementById('blogIframe').style.height = parseInt(newHeight,10) + 10 + 'px';
}
Et voila, you have a robust resizer that triggers once the page is fully rendered with no nasty contentdocument vs contentWindow fiddling :)
Sure, now people will see your iframe at default height first, but this can be easily handled by hiding your iframe at first and just showing a 'loading' image. Then, when the resizeIframe function kicks in, put two extra lines in there that will hide the loading image, and show the iframe for that faux Ajax look.
Of course, this only works from the same domain, so you may want to have a proxy PHP script to embed this stuff, and once you go there, you might as well just embed your blog's RSS feed directly into your site with PHP.
You can do this with JavaScript.
document.getElementById('foo').height = document.getElementById('foo').contentWindow.document.body.scrollHeight + "px";
Fitting IFRAME contents is kind of an easy thing to find on Google. Here's one solution:
<script type="text/javascript">
function autoIframe(frameId) {
try {
frame = document.getElementById(frameId);
innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
objToResize = (frame.style) ? frame.style : frame;
objToResize.height = innerDoc.body.scrollHeight + 10;
}
catch(err) {
window.status = err.message;
}
}
</script>
This of course doesn't solve the cross-domain problem you are having... Setting document.domain might help if these sites are in the same place. I don't think there is a solution if you are iframe-ing random sites.
Here's my solution to the problem using MooTools which works in Firefox 3.6, Safari 4.0.4 and Internet Explorer 7:
var iframe_container = $('iframe_container_id');
var iframe_style = {
height: 300,
width: '100%'
};
if (!Browser.Engine.trident) {
// IE has hasLayout issues if iframe display is none, so don't use the loading class
iframe_container.addClass('loading');
iframe_style.display = 'none';
}
this.iframe = new IFrame({
frameBorder: 0,
src: "http://www.youriframeurl.com/",
styles: iframe_style,
events: {
'load': function() {
var innerDoc = (this.contentDocument) ? this.contentDocument : this.contentWindow.document;
var h = this.measure(function(){
return innerDoc.body.scrollHeight;
});
this.setStyles({
height: h.toInt(),
display: 'block'
});
if (!Browser.Engine.trident) {
iframe_container.removeClass('loading');
}
}
}
}).inject(iframe_container);
Style the "loading" class to show an Ajax loading graphic in the middle of the iframe container. Then for browsers other than Internet Explorer, it will display the full height IFRAME once the loading of its content is complete and remove the loading graphic.
Below is my onload event handler.
I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments.
This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5.
It might need some extra tweaking, but the general idea should be clear.
function onLoadDialog(frame) {
try {
var body = frame.contentDocument.body;
var $body = $(body);
var $frame = $(frame);
var contentDiv = frame.parentNode;
var $contentDiv = $(contentDiv);
var savedShow = $contentDiv.dialog('option', 'show');
var position = $contentDiv.dialog('option', 'position');
// disable show effect to enable re-positioning (UI bug?)
$contentDiv.dialog('option', 'show', null);
// show dialog, otherwise sizing won't work
$contentDiv.dialog('open');
// Maximize frame width in order to determine minimal scrollHeight
$frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
contentDiv.offsetWidth + frame.offsetWidth);
var minScrollHeight = body.scrollHeight;
var maxWidth = body.offsetWidth;
var minWidth = 0;
// decrease frame width until scrollHeight starts to grow (wrapping)
while (Math.abs(maxWidth - minWidth) > 10) {
var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
$body.css('width', width);
if (body.scrollHeight > minScrollHeight) {
minWidth = width;
} else {
maxWidth = width;
}
}
$frame.css('width', maxWidth);
// use maximum height to avoid vertical scrollbar (if possible)
var maxHeight = $contentDiv.dialog('option', 'maxHeight')
$frame.css('height', maxHeight);
$body.css('width', '');
// correct for vertical scrollbar (if necessary)
while (body.clientWidth < maxWidth) {
$frame.css('width', maxWidth + (maxWidth - body.clientWidth));
}
var minScrollWidth = body.scrollWidth;
var minHeight = Math.min(minScrollHeight, maxHeight);
// descrease frame height until scrollWidth decreases (wrapping)
while (Math.abs(maxHeight - minHeight) > 10) {
var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
$body.css('height', height);
if (body.scrollWidth < minScrollWidth) {
minHeight = height;
} else {
maxHeight = height;
}
}
$frame.css('height', maxHeight);
$body.css('height', '');
// reset widths to 'auto' where possible
$contentDiv.css('width', 'auto');
$contentDiv.css('height', 'auto');
$contentDiv.dialog('option', 'width', 'auto');
// re-position the dialog
$contentDiv.dialog('option', 'position', position);
// hide dialog
$contentDiv.dialog('close');
// restore show effect
$contentDiv.dialog('option', 'show', savedShow);
// open using show effect
$contentDiv.dialog('open');
// remove show effect for consecutive requests
$contentDiv.dialog('option', 'show', null);
return;
}
//An error is raised if the IFrame domain != its container's domain
catch (e) {
window.status = 'Error: ' + e.number + '; ' + e.description;
alert('Error: ' + e.number + '; ' + e.description);
}
};
#SchizoDuckie's answer is very elegant and lightweight, but due to Webkit's lack of implementation for scrollHeight (see here), does not work on Webkit-based browsers (Safari, Chrome, various and sundry mobile platforms).
For this basic idea to work on Webkit along with Gecko and Trident browsers, one need only replace
<body onload='parent.resizeIframe(document.body.scrollHeight)'>
with
<body onload='parent.resizeIframe(document.body.offsetHeight)'>
So long as everything is on the same domain, this works quite well.
I just spent the better part of 3 days wrestling with this. I'm working on an application that loads other applications into itself while maintaining a fixed header and a fixed footer. Here's what I've come up with. (I also used EasyXDM, with success, but pulled it out later to use this solution.)
Make sure to run this code AFTER the <iframe> exists in the DOM. Put it into the page that pulls in the iframe (the parent).
// get the iframe
var theFrame = $("#myIframe");
// set its height to the height of the window minus the combined height of fixed header and footer
theFrame.height(Number($(window).height()) - 80);
function resizeIframe() {
theFrame.height(Number($(window).height()) - 80);
}
// setup a resize method to fire off resizeIframe.
// use timeout to filter out unnecessary firing.
var TO = false;
$(window).resize(function() {
if (TO !== false) clearTimeout(TO);
TO = setTimeout(resizeIframe, 500); //500 is time in miliseconds
});
The trick is to acquire all the necessary iframe events from an external script. For instance, you have a script which creates the iFrame using document.createElement; in this same script you temporarily have access to the contents of the iFrame.
var dFrame = document.createElement("iframe");
dFrame.src = "http://www.example.com";
// Acquire onload and resize the iframe
dFrame.onload = function()
{
// Setting the content window's resize function tells us when we've changed the height of the internal document
// It also only needs to do what onload does, so just have it call onload
dFrame.contentWindow.onresize = function() { dFrame.onload() };
dFrame.style.height = dFrame.contentWindow.document.body.scrollHeight + "px";
}
window.onresize = function() {
dFrame.onload();
}
This works because dFrame stays in scope in those functions, giving you access to the external iFrame element from within the scope of the frame, allowing you to see the actual document height and expand it as necessary. This example will work in firefox but nowhere else; I could give you the workarounds, but you can figure out the rest ;)
Try this, you can change for even when you want. this example use jQuery.
$('#iframe').live('mousemove', function (event) {
var theFrame = $(this, parent.document.body);
this.height($(document.body).height() - 350);
});
Try using scrolling=no attribute on the iframe tag. Mozilla also has an overflow-x and overflow-y CSS property you may look into.
In terms of the height, you could also try height=100% on the iframe tag.

Categories