Difference in value on page load and page refresh - javascript

So i am trying to read the height and width of img elements created via jquery.
This is the code i am trying to execute
$(document).ready(function()
{
$.ajax({
url: 'res/script/getImage.php',
type: 'POST',
data: {
param : 'Load'
},
success: function(result)
{
ImageArray = JSON.parse(result);
for(i=0; i<ImageArray.length; i++)
{
//Read the Image element and update to gallery
document.getElementById("gallery").innerHTML += ImageElement;
ImageArrayComplete[ImageCounter] = ImageArray[i].image;
UserArrayComplete[ImageCounter] = ImageArray[i].user;
}
//Create Canvas
$('#gallery img').each(function() {
console.log(this);
console.log('Width=' + this.width+ 'Height='+this.height);
createCanvas(this);
});
}
});
});
The output of console.log(this); is the path for image which is as expected.
But the output of console.log('Width=' + this.width+ 'Height='+this.height); is 0 for both width and height during initial page load.
The value then resets to actual width of 200 once page is refreshed.
There is no other error thrown and happens in both firefox and chrome. What am i missing here?

Are you sure the img select has the height and width values?

your ImageElement object is undefined. try this:
change
document.getElementById("gallery").innerHTML += ImageElement;
to
$('<img/>').attr('src', ImageArray[i].image).appendTo($('#gallery'));
and this object doesn't have a height and width attribute. if you wanna get height of it, use :
console.log('Width=' + $(this).width() + 'Height=' + $(this).height());

Related

The image doesn't get more wide

I was trying to make a mini image editor with a width and height function. The image should keep getting more wide after button is clicked. I tried debugging with printing the width in the console and it did but the image didn't get wider. I also tried many other variations and all of them didn't work.
so, here is my code:
function go1(){
setInterval( function() {document.getElementById("testimage").style.width + 10}, 250)
}
Your first problem is that while you are calculating a new width, you are aren't setting the new width in your code.
The second problem is that IMG tags don't use the width style. Instead, they have a width attribute
function go1(){
setInterval( function() {
var im = document.getElementById("testimage");
var newWidth = (im.getAttribute("width") ? im.getAttribute("width") : 0) + 10;
im.setAttribute("width", newWidth);
}, 250)
}

How to get the height of a div after its content is loaded?

im trying to get the size of an <img> in the <window> by checking width and height of its container.
i used .load() to wait until the <img> is loaded.
On pageload the size is still 0.
I only get the correct height on resize.
What is wrong here?
EDIT: to get the correct size i added .contents()
$(document).ready(function(){
$('img').load(function(){
function size(){
var height = $('#size').contents()height();
var width = $('#size').contents().width();
$('#size').find('p.size').remove();
$('#size').append('<p class="size">' + height + '-' + width + '</p>');
};
$(window).load(size);
$(window).resize(size);
});
});
you define a function, but you don't invoke it
place size(); after $(window).resize(size);
EDIT: whole code with some improvements
$(document).ready(function(){
function size(){
var height = $('#size').height();
var width = $('#size').width();
$('#size').find('p.size').remove();
$('#size').append('<p class="size">' + height + '-' + width + '</p>');
}
$(window).load(size);
$(window).resize(size);
$('img').load(size);
});

Dynamic content - transitions NOT working

Alright let's see if I can explain this properly.
I am writing my own jQuery photo gallery. It loads the contents of the gallery using AJAX, calling upon a Web Method which returns a string which is an array filled with JSON objects containing data (i.e. the file name and the file path of the image and the file path for the image's thumbnail) on every file in the folder passed to it.
Like 'a so:
$(".Title").click(function (e) {
Populate($(this).text());
function Populate(folder) {
$.ajax({
type: "POST",
url: "Filenames.asmx/GetFiles",
contentType: "application/json; charset=utf-8",
data: '{ "folderName" : "'+folder+'"}',
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
...//more code follows
Anyway, so, we have our OnSuccess() function:
function OnSuccess(response) {
var $thumbs = $('#Gallery_Top .viewPane .thumbPanel');
images = $.parseJSON(response.d);
$thumbs.children().each(function () {
//$(this).animate({ 'width': '0px', 'opacity': '0' }, 500).remove();
$(this).transition({ opacity: 0 }).remove();
});
//make sure the thumb reel resets to its original position
$thumbs.css('left', '0px');
for (var i = 0; i < images.length; i++) {
InsertHTML(images[i].thumbHref);
}
}
So far so good.
In the InsertHTML() function, I have to do a few things...
function InsertHTML(data) {
//create the thumbnail image
var $thumb = $('<img src="' + data + '" alt=""/>');
//set its default class to inactive
$thumb.addClass('inactive');
//bind a function to the thumbnail's click event
$thumb.bind("click", function () {
//make sure we have the current image assigned
//for navigation purposes.
$currentImage = $(this);
//remove the main image from the viewing pane
$('#Gallery_Top .viewPane .mainImage .showImage').children().animate({'opacity':'0'},500,'easeOutSine').remove();
//set all of the thumbnails to inactive
$(this).parent().children().each(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$(this).addClass('inactive');
}
});
//set the clicked thumbnail active
$(this).addClass('active');
//get the URL for the related image
var href = data.replace('Thumbs\\', '');
href = href.replace('_thumb', '');
var $image = $('<img src="' + href + '" alt=""/>');
$image.addClass('mainImg');
$('#Gallery_Top .viewPane .mainImage .showImage')
.append($image)
.animate({ 'opacity': '1' }, 500, 'easeInSine');
});
$('#Gallery_Top .viewPane .thumbPanel').append($thumb);
}
Okay, so anyway, what's not working is every transition after the first time I click a thumbnail image. The first time I click a thumbnail, the photo fades in nicely. Ever after that, there's no transition at all.
Been yanking my hair out for about 3 hours trying to figure out a way around.
By the way, here's some CSS.
.mainImg{
display: block;
width: 75%;
height: 75%;
margin: 0 auto;
margin-top: 150px;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
EUREKA SUCCESS I DID IT.
It never fails. I beat my head against a wall for three or four hours, trying so hard not to have to come on here and ask, then half an hour after I finally break down and ask a question, I figure it out. It's probably motivation from the shame of not knowing how to do something.
var $image = $('<img src="' + href + '" alt=""/>');
$image.on('load', function () {
$(this).animate({ 'opacity': '1' }, 500, 'easeOutSine');
});
$image.addClass('mainImg');
$image.css('opacity', '0');
$('#Gallery_Top .viewPane .mainImage .showImage').append($image);

Scroll Top = Scroll Height not working in Chrome

This is the js that I have in my js file
function refreshChat()
{
//speed up by selecting the div only once
var shoutbox = $("#shoutbox");
//get the height of the scroll (if any)
var oldScrollH = shoutbox.attr("scrollHeight") - 20;
//the ajax request
$.ajax({
url: 'shoutbox/update.php',
//disable cache
cache: false,
success: function(html) {
//update the shoutbox
shoutbox.html(html);
//get the heigth of the scroll after the update
var newScrollH = shoutbox.attr("scrollHeight") - 20;
if(newScrollH > oldScrollH)
{
//*move* the scroll down using an animation :)
shoutbox.animate({scrollTop: newScrollH}, 1);
}
}
});
}
//set the refreshChat function to run every *refreshSeconds*
setInterval(refreshChat, refreshSeconds);
});
it works fine in Firefox and IE, but with Google Chrome it constantly flicks. It will scroll to the bottom on page load, but when it calls to the function refreshChat it moves back up about halfway up the div.
I also have this in my <head>
$(document).ready(function(){
//speed up by selecting the div only once
var shoutbox = $("#shoutbox");
//get the height of the scroll (if any)
var oldScrollH = shoutbox.attr("scrollHeight");
//the ajax request
$.ajax({
url: 'shoutbox/update.php',
//disable cache
cache: false,
success: function(html) {
//update the shoutbox
shoutbox.html(html);
//get the heigth of the scroll after the update
var newScrollH = shoutbox.attr("scrollHeight");
if(newScrollH > oldScrollH)
{
//*move* the scroll down using an animation :)
shoutbox.animate({scrollTop: newScrollH}, 1);
}
}
})
});
so that it will auto load the shoutbox on page load, could this be conflicting with it? It seems logical, but I don't want users to have to wait 3 seconds for the shoutbox to initially load.
You need to convert string to int.
scrollHeight is custom attribute and i guess its dynamically added so it must string thats why you need to cast it to int.
parseInt(shoutbox.attr("scrollHeight"));
try this, hope this will solve it.

Getting the width from an scaled image

I'm using Jquery to get the width of an image once it is appended to the body. Have a look at this fiddle to get an understanding of what I'm doing.
What I want to do is add each element with a constrained height and read what the respective width is once after it is scaled. The problem as you will see is that the console.log is giving me the value 0 for the width.
Use jQuery .load() function to do all the calculation after image load:
var number = 0;
$(document).ready(function(){
setInterval(function(){
console.log();
$('.container').prepend(
$('<img/>').attr({
src: "http://www.upress.umn.edu/book-division/images-1/other images/blockc.gif/image_thumb"
id:'img' + (number++)
}).load(function(){
console.log($(this).width())
})
},3000);
});​
http://jsfiddle.net/w7rcn/
The width was being "read" before the image could fully download.
So, we used the same concept, but applied it after the img load event had fired:
$('#img' + String(number)).load(function() {
console.log($(this).width());
});
Mohsen and Justice are right. However, you can still simplify a bit:
var number = 0;
$(document).ready(function(){
setInterval(function(){
console.log();
$('.container').prepend($('<img '
+ 'id="img'+number+'"src="http://www.upress.umn.edu/'
+ 'book-division/images-1/other-'
+ 'images/blockc.gif/image_thumb">').load(function() {
console.log($(this).width());
}));
number++;
}, 3000);
});​

Categories