i am trying to make a gallery viewer on which the webpage shows thumbs of the real images and then when the image is clicked, the original image(with original size) is displayed, the div which holds the html "img" element is changed to visible(else by default it is set to hidden) and meanwhile am trying to get the dimensions of the image so that i can center the images of different dimensions properly acc. to their width and the problem am having is that whenever i click any thumb for the first time after the page is loaded, the statement which gets the width of the image sends 0, and after that when clicking any other image without reloading the page (including the previous one) it shows the previous image's dimension and sometimes it works and sometimes not(mostly doesn't), please help me out. The javascript code is below.
// JavaScript Document
$(document).ready(function() {
$.post(
"loadup.php",
{
refer:"yes"
},function(response){
$("#gallery_view_tab").html(response);
initAll();
});
});
function initAll(){
$("<div id='imgViewer'></div>").appendTo("body"); //set up image viewer
$("#imgViewer").insertBefore("#monster_wrap"); //set before monster_wrap
var thumbimgs = $(".thumbimg");
for(i=0; i<thumbimgs.length; i++){
var thumbimg = thumbimgs[i].id;
var thumbid = '#'+thumbimg;
$(thumbid).click(loadImgviewer);
}
}
function loadImgviewer(){
var imgLink = this.getAttribute("data-link");
$("<img id='closeImgviewer' src='images/close.png' /><img src='' id='imgview' />").appendTo("#imgViewer");
$("#imgview").attr('src', imgLink);
$("#imgViewer").css('visibility', 'visible');
imgwidth = $("#imgview").width();
screenwidth = $(window).width();
var pos = (screenwidth - imgwidth)/2;
$("#log").html(pos);
$("#imgview").css('margin-left', pos);
$("#closeImgviewer").click(unloadImgviewer); //set click event handler on image view closer
}
function unloadImgviewer(){
$("#imgViewer").css('visibility', 'hidden');
$("#imgview").attr('src', '');
$("#imgViewer").empty();
}
I just rewrote your code a little.
$(document).ready(function() {
$.post(
"loadup.php",
{
refer:"yes"
},
function(response){
$("#gallery_view_tab").html(response);
initAll();
}
);
});
function initAll(){
$("<div id='imgViewer'></div>").appendTo("body"); //set up image viewer
$("#imgViewer").insertBefore("#monster_wrap"); //set before monster_wrap
$(".thumbimg").on('click', loadImgviewer);
}
function loadImgviewer(){
var imgwidth, pos,
screenwidth = $(window).width();
var imgLink = this.getAttribute("data-link");
$("<img id='closeImgviewer' src='images/close.png' /><img src='' id='imgview' />").appendTo("#imgViewer");
$("#imgview").attr('src', imgLink).on('load',function(evt){
imgwidth = $(this).width();
pos = (screenwidth - imgwidth) / 2;
$("#log").html(pos);
$("#imgview").css('margin-left', pos);
$("#imgViewer").css('visibility', 'visible');
};
$("#closeImgviewer").click(unloadImgviewer); //set click event handler on image view closer
}
function unloadImgviewer(){
$("#imgViewer").css('visibility', 'hidden');
$("#imgview").attr('src', '');
$("#imgViewer").empty();
}
Please try it our. Didn't try it but I think it should work.
Related
From a html5 drag'n drop plugin, i'm getting a data uri of dropped images (or from a file input..).Then i'm setting it as an image src :
$("#preview").attr("src",image);
Now, i need to make some actions depending on the image dimensions. I tried this by two ways :
1) - By getting the image height and width from the uri data directly (i got this piece of code from here
var curHeight;
var curWidth;
function getImgSize(imgSrc)
{
var newImg = new Image();
newImg.src = imgSrc;
curHeight = newImg.height;
curWidth = newImg.width;
}
getImgSize(The_data_uri);
2) by testing on the created image on the html :(here i created two booleans)
var lt = function(v1, v2){
return v1 < v2;
}
var gt400 = (lt(400,parseInt($("#preview").css('width').replace('px', ''))) && lt(400,parseInt($("#preview").css('height').replace('px', ''))) && !window['cropIsOn'] );
var eq400 = (parseInt($("#preview").css('width').replace('px', ''))==400 && parseInt($("#preview").css('height').replace('px', ''))==400) && !window['cropIsOn'] ;
On chrome i always got the correct dimensions and therefore tests on dimentions are corrects. However, on firefox it's not correct (i got wrong width and height values). by the way, i'm not trying with different image format for each time(i'm only using jpg images).
i wish to understand why firfox isn't stable about reading height and width.Cheers!
-EDIT-
the image which i'm trying to get its dimensions is inside a hidden div
<div id="prview_img_wrap" style="position:absolute;top:465px; left:200px;z-index:8; width:100px;height:100px;overflow:hidden;margin-left:5px; border:2px dashed white; visibility:hidden;">
<img src="" id="preview" />
</div>
The height and width of the image are only available after the image is loaded. so this is the correct way:
var curHeight;
var curWidth;
function getImgSize(imgSrc){
var newImg = new Image();
newImg.onload = function () {
curHeight = this.height;
curWidth = this.width;
};
newImg.src = imgSrc;
}
In our site we are accessing our images or the image source is like
<img src="image_manage.php&type=resize&id=12" />
My issue is, to get the image height and width using this source in jquery.
I write a code to get the width and height
photograf = new Image();
photograf.src = '/image_manage.php&type=resize&id=12';
var width = photograf.width;
var height = photograf.height;
But I got the value zero for both height and width what is the issue?
Try this code:
var oImage = new Image();
oImage.onload = function(){
this.width// width of loaded image
}
oImage.src = '/path/to/image.gif';
Or something like that is better:
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
Try with this
width = $("img").attr('width'); //can also $("img").width();
hight = $("img").attr('height'); //can also $("img").height();
you can try this
width = $("img").prop('width');
hight = $("img").prop('height');
Dont forget to put js code in load or document ready events
$(document).ready(function(){
var height = $('img').prop('height');
var width= $('img').prop('width');
alert('Height :'+height+' AND '+'width :'+width);
});
here is the running example
Example
jsfiddle
Use jQuery width() and height() functions:
jQuery(function(){
var $width = jQuery("img").width();
var $height = jQuery("img").height();
});
The image isn't loaded yet when you ask for its size. The onLoad method is helpful for this purpose.
photograf = new Image();
photograf.src = '/image_manage.php&type=resize&id=12';
photograf.onLoad = function(){
var width = this.width;
var height = this.height;
};
You'll have to wait for the image to load in order to detect it's size.
$("#imgElement").attr('src',photograf.src).load(function(){
var w = $("imgElement").width();
var h = $("imgElement").height();
});
Here I am setting the src parameter of the image and using jQuery's load() function to detect when the image has been successfully loaded.
Reference -
load()
I need to get the width & height of a CSS background image and inject it into document.ready javascript. Something like:
$(document).ready(function(){
img = new Image();
img.src = "images/tester.jpg";
$('body').css('background', 'url(' + img.src + ')');
$('body').css('background-size', img.width + 'px' + img.height + 'px');
});
The problem is, the image width and height aren't loaded in at the time of document.ready, so the values are blank. (They're accessible from console, but not before).
img.onload = function() { ... } retrieves the width and height, but DOM $(element) calls aren't accessible from within img.onload.
In short, I'm a little rusty on my javascript, and can't figure out how to sync image params into the DOM. Any help appreciated
EDIT: jQuery version is 1.4.4, cannot be updated.
You could use $.holdReady() to prevent jQuery's ready method from firing until all of your images have loaded. At that point, their width's and height's would be immediately available.
Star by calling $.holdReady(true). Within the onload method of each image, check to see how many images have been loaded all together, and if that matches the number of expected images, you can $.holdReady(false) to fire the ready event.
If you don't have access to $.holdReady(), you could simply wait to spit out your HTML until all of the images have loaded by still calling a function:
var images = { 'loaded': 0,
'images': [
"http://placekitten.com/500/500",
"http://placekitten.com/450/450",
"http://placekitten.com/400/400",
"http://placekitten.com/350/340",
"http://placekitten.com/300/300",
"http://placekitten.com/250/250",
"http://placekitten.com/200/200",
"http://placekitten.com/150/150",
"http://placekitten.com/100/100"
]};
function outputMarkup() {
if ( ++images.loaded === images.images.length ) {
/* Draw HTML with Image Widths */
}
}
for ( var i = 0; i < images.images.length; i++ ) {
var img = new Image();
img.onload = function(){
outputMarkup();
};
img.src = images.images[i];
}
I have an image element with a spinner gif. I later dynamically change the src of that image with jQuery, and I want to get the actual width and height of the new image. Here is my code:
function loadImage() {
$('#uploaded-image').load(function() {
var img = document.getElementById('uploaded-image');
// These statements return the correct values in FF and Chrome but not IE
imgWidth = img.clientWidth;
imgHeight = img.clientHeight;
});
$('#uploaded-image').removeAttr('width').removeAttr('height').attr('src', imgUrl);
}
This works perfectly in Chrome and Firefox, but IE always returns the size of the original spinner gif instead of the new image.
How can I get the width and height of the new image in IE?
Notes:
I've tried the jQuery .width() and .height() methods in addition to the pure Javascript approach, with the same results.
The .load event is being fired as expected in all browsers.
Use offsetHeight and offsetWidth in IE.
Check this out in your IE: http://jsbin.com/abopih/5
var imgUrl = "http://www.google.com/intl/en_com/images/srpr/logo3w.png";
var img = document.getElementById('uploaded-image');
$('#uploaded-image').click(function() {
imgWidth = img.clientWidth;
imgHeight = img.clientHeight;
$('#uploaded-image').removeAttr('width').removeAttr('height').attr('src', imgUrl);
console.info('clientWidth: ', img.clientWidth);
console.info('clientHeight: ', img.clientHeight);
console.info('offsetWidth: ', img.offsetWidth);
console.info('offsetWidth: ', img.offsetWidth);
});
You could create a hidden div and place the image in there in order to get the size. Just make sure the hidden div isn't done with display:none, because then it will have no dimensions. Use visibility:hidden, grab the dimensions, and then remove it.
Make sure you remove css height and width as well:
$('#uploaded-image').css({ height: "auto", width: "auto" });
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" id="file" />
<script type="text/javascript" charset="utf-8">
$("#file").change(function(e) {
var file, img;
file = document.getElementById("file");
if (file!=null) {
img = new Image();
img.src = file.value;
img.onload = function() {
alert(img.width + " " + img.height);
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
};
}
});
</script>
It seems to be a cache problem.
Add this to your image source url:
imgUrl += new Date().getTime();
This code is meant for a real estate website I am updating for my company. Basically, There is a table with the property name, address, etc, and an image. Originally, I was coding this website in ASP.net switch over to regular Javascript for a few reasons (hosting overhead etc).
Sections of this code are from a few different tutorials out there, one of which is an ASP.net modal div image "enlarger" tutorial, which is sort of the basis combined with a few other sites. I have yet to comment in their names etc, but I plan on giving them credit in the code. Thier links are below before I post my code.
http://archive.aspsnippets.com/post/2009/07/06/Image-Gallery-using-ASPNet-GridView-control.aspx
My code is essentially as follows (I will trim the fat and excess line breaks in the style section):
First are the modal style tags from that tutorial by Mudassar Khan (partially relevant):
<style>
body {margin:0;padding:0;height:100%;}
.modal {display: none;position: absolute;top: 0px;left: 0px;background-color:black;z-index:100;opacity: 0.8; filter: alpha(opacity=60);-moz-opacity:0.8;min-height: 100%;}
&#divImage{display: none;z-index: 1000;position: fixed;top: 0;left: 0;background-color:White;height: 550px;width: 600px;padding: 3px;border: solid 1px black;}
<style>
Then comes his script, which I may have tweaked here and there:
<script type="text/javascript">
function LoadDiv(url) {
var img = new Image();
var bcgDiv = document.getElementById("divBackground");
var imgDiv = document.getElementById("divImage");
var imgFull = document.getElementById("imgFull");
var imgLoader = document.getElementById("imgLoader");
img.src = url;
var tcopy = img.src.slice(0,(img.src.length-4)) + "_big.png";
img.src = tcopy;
img.onload = function () {
imgFull.src = tcopy
imgFull.style.display = "block";
imgLoader.style.display = "none";
};
var width = document.body.clientWidth;
if (document.body.clientHeight > document.body.scrollHeight) {
bcgDiv.style.height = document.body.clientHeight + "px";
}
else {
bcgDiv.style.height = document.body.scrollHeight + "px";
}
imgDiv.style.left = (width - 650) / 2 + "px";
imgDiv.style.top = "20px";
bcgDiv.style.width = "100%";
bcgDiv.style.display = "block";
imgDiv.style.display = "block";
return false;
}
function HideDiv() {
var bcgDiv = document.getElementById("divBackground");
var imgDiv = document.getElementById("divImage");
var imgFull = document.getElementById("imgFull");
imgLoader.style.display = "block"; // I added as it seems to bring back the loader gif
if (bcgDiv != null) {
bcgDiv.style.display = "none";
imgDiv.style.display = "none";
imgFull.style.display = "none";
}
}
</script>
Now All this above script gets called upon a onClick Event Handler on an image of each of the real estate companies properties. This will work well to both preload images with the little animated gif and the close button works fine. It works on more than one image, BUT if the image is already preloaded, I cant think of a way to force the redisplay of an already preloaded image if a user clicks on the photo, then clicks close to hide the div tag and then clicks on the same preloaded image.
That event handler looks like this:
img onClick="return LoadDiv(this.src);" src="http://www.ourcompany.com/images/prop_thumbs/Some_plaza.png" style="min-width:200 px;max-height:150 px;max-width:200 px;"
I thought global booleans would work, but then I realized, theres no telling which and what is preloaded, so the boolean might not help if you can't pass something meaningful back and forth.
I'm not asking any one to do my work for me, however I would appreciate suggestions in the right direction.
Regards and TIA!
You could make a array of all of the images with key values of loaded. For instance.
image_list = {image1:false,image2:true,image3:false};
true and false being loaded or not loaded. When an image is clicked just update the array.
image_list[image1] = true;
Did this really quick, so my syntax might be off, feel free to correct me or berate me...
Yay!!! Figured it out with the help of both jhanifen and the guy who did the tutorial I used (he actually emailed me). My code is below (its an excerpt, but you'll get the idea):
images = new Array(30);
//need to define each image to be in array
images[0]="website/images/prop_thumbs/property1_big.png";
images[1]="website/images/prop_thumbs/property2_big.png";
images[2]="website/images/prop_thumbs/property3_big.png";
//This continues for some time
imagesLoaded = new Array(30);
// per stack overflow person suggestion make array of bool values; initialize them all to false on page load
function onLoadScript() {
for (i = 0; i < imagesLoaded.length; ++ i)
{
imagesLoaded [i] = false;
}
}
// the above is called onLoad in body tag
// Changes the script for Loading the Div tag are below:
function LoadDiv(imgNum) {
var img = new Image();
var bcgDiv = document.getElementById("divBackground");
var imgDiv = document.getElementById("divImage");
var imgFull = document.getElementById("imgFull");
var imgLoader = document.getElementById("imgLoader");
img.src = images[imgNum];
if(imagesLoaded[imgNum] = true)
{ // this statement triggers same as onload below!
imgFull.src = img.src
imgFull.style.display = "block";
imgLoader.style.display = "none";
}
img.onload = function () {
imgFull.src = img.src
imgFull.style.display = "block";
imgLoader.style.display = "none";
imagesLoaded[imgNum] = true;
};
The rest of the document is the same except I changed the onClick event handler for the property images to LoadDiv(and some sequential number);
Thanks to all for your help! Particular props to both Mudassar Khan and jhanifen!