jquery not getting the image values on server - javascript

I have this javascript that's supposed to get the image's actual width and height. It works when I test locally on 127.0.0.1:8000 console logs on the snapshot but on the server it fails returns 0 as the image width and height.
Tried nesting the code in jquery ready but it does trigger before the image fully loads so I believe this is the issue.
here's the javascript
$(function() {
$(document).ready(function() {
$('.lynk-section img').each(function() {
var width = $(this)[0].naturalWidth;
console.log(width);
//$(this).css('max-width', width+'px');
var height = $(this)[0].naturalHeight;
console.log(height);
//$(this).css('max-height', height+'px');
});
});
});

$(function() { and $(document).ready(function() { are the same thing (the first one is a shorthand), you only need one. But anyway, this will just wait for all the HTML code to be present in the page, not for the assets to be loaded. As #Rory said, window.load will wait for the images to be loaded, so you can then grab their dimensions.

you have to use the onload event of the image, or maybe you just have to use window.onload event
//....
$('img').each(function() {
$(this).on("load", function(){
console.log("width: ", this.naturalWidth);
console.log("height: ", this.naturalHeight);
});
});
//....
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://via.placeholder.com/50x150">
<img src="http://via.placeholder.com/100x150">
<img src="http://via.placeholder.com/200x150">

Put your code under window load event.
$(function() {
$(document).on('load',function() {
// Your code to measure image dimensions should go here.
});
});

Related

Why is this java script not working?

In reference to this post: How to display loading image while actual image is downloading
I have the following code, but for some reason I cannot get the #loader_img to hide. I would also like to add a preloader because the large image is really heavy, but I want to keep it simple if possible since I am new to javascript...
<img id="loader_img" src="img/ajax-loader.gif" alt="Loading..." />
<div class="magnifier" style="height: 584px; width: 467px; margin: 20px;">
<div class="maglens">
<img id="imgload" src="img/largeimage.jpg" />
</div>
</div>
JS:
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
$("#imgload").on('load', function(){
// hide/remove the loading image
$("#loader_img").hide();
});
Any help will be much appreciated! Thank you!
The image's load event is almost certainly firing before you hook the event. Since it's already fired when you hook the event, you never see it occur.
Also, you start out hiding the image (#imgload), but you never then show it.
To ensure that you get the event, you have to hook load before setting the image's src.
Alternately, you can use the image's complete property to know if it's already been loaded:
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
var img = $("#imgload");
if (img[0].complete) {
imageDone();
} else {
img.on('load', imageDone);
}
function imageDone() {
// hide/remove the loading image
$("#loader_img").hide();
// And show the image!
img.show();
}
You also have to ensure that the code above runs after the elements have been created. The best way to do that is to put your script tag containing the code after the elements it refers to in the HTML (usually putting it just before the closing </body> tag works well). As a second-best solution, you can use jQuery's ready function. Either way, you'll still need to handle the possibility the load event has already fired.
Here's an example:
<div id="loader_img">Loading</div>
<div class="content">
<img id="imgload" src="http://i.stack.imgur.com/rTQCa.jpg?s=512&g=1" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function() { // Avoid creating globals
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
var img = $("#imgload");
if (img[0].complete) {
console.log("Complete");
imageDone();
} else {
console.log("Wait for load");
img.on('load', imageDone);
}
function imageDone() {
console.log("Loaded");
// hide/remove the loading image
$("#loader_img").fadeOut();
// And show the image!
img.show();
}
})();
</script>
Hi you may use this method. jQuery.ready()I have tried on my computer and it's okay this way.
BTW, you forgot to let the "imgload" show again.
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
$("#imgload").ready(function(){
// hide/remove the loading image
$("#loader_img").hide();
$("#imgload").show(); // show the loaded img again
});
I think that the script is executed before the DOM is loaded.
Take your script and put it between:
$(function () {
//Your code here
});
This will insure that the code will run after the DOM is loaded.

Hiding an image until the document is loaded, then applying effects to it

I'm trying to find a simple, but bulletproof way of hiding an image until it's loaded, and then giving it some jQuery effects (e.g. fadeIn) but all the methods I've found seem to have some issues. For example, this solution:
<img id="photo" src="bigimage.jpg" style="display:none" />
$("#photo").load(function() {
$(this).fadeIn("slow");
});
May not trigger if the image is loaded before the DOM is ready (load() won't fire).
So I wrote the following, which only adds the URL once the image has definitely loaded...
$.fn.ImageLoad = function(url){
$image = $(this);
$("<img >").attr("src", url).load(function(){
$image.attr("src", url);
});
return $image;
};
$("#cast").ImageLoad("http://pas-wordpress-media.s3.amazonaws.com/wp-content/uploads/2013/08/Google-Office-Building-in-NYC.jpg").fadeIn("slow");
But it only runs the fadeIn("slow") once the image has been cached by the browser. The first time it loads, it just appears with no effects.
See your yourself here: http://jsfiddle.net/KKn4N/
Is there any way I can fix this?
Here is my version. Works every single time and completely cross browser.
$.fn.ImageLoad = function(url){
$this = $(this);
$this.hide().on('load', function(){
$this.fadeIn();
});
this[0].src = url;
};
The key is to
do the fade inside a callback
hide first
listen for the .load before you set the .src
DEMO
Yea, load the image first, then attach the fadeIn afterwards.
$.fn.ImageLoad = function(url){
$image = $(this);
$("<img >").attr("src", url).load(function(){
$image.attr("src", url);
});
return $image;
};
$("#cast").ImageLoad("http://www.wired.com/wiredenterprise/wp-content/uploads/2013/07/ff_googleinfrastructure_large.jpg");
$("#cast").fadeIn("slow");
Try this
<img
id="cast"
style="display:none"
src="http://pas-wordpress-media.s3.amazonaws.com/wp-content/uploads/2013/08/Google-Office-Building-in-NYC.jpg"
onload="$(document).ready(function(){$('#cast').fadeIn('slow')})"
/>
Not sure if I get it correctly - I'm assuming you mean hide all images when page loads until all images are loaded and then fade them in?
If so, then why not just set display:none on images (maybe give them a class .hidden {display:none}) and then wait for window load event (i.e. all loaded) and trigger fade on all images - they will then nicely all fade in at the same time.
$('img.hidden').fadeIn('slow');
Example:
html
<img class=hidden src=http://cdn-4.lifehack.org/wp-content/files/2013/09/javascript-logo.png></img>
css
.hidden{
display:none;
}
js
$(window).load(function(){
$('img.hidden').fadeIn('slow');
});

Function not being called when I return to the page

I have two images, the first image can be any size and I'd like the second image, right beside it to be the same height as the first image. I wrote the following code:
<script>
$(function() {
$("#first").load(function() {
var imgheight = $(this).height();
$("#first_papers").css("height", imgheight);
});
});
</script>
The above code works fine. The problem is that when I visit another page on the site and then return to the main page the function doesn't seem to be called. What happens insteadis that the second image is appearing at its full height instead of the shorter height of the first image.
Any ideas on how to fix this?
For consistent behavior whenever the page loads I would take it out of the anonymous function its in and put it in a $(document).ready function.
<script>
$(document).ready(function(){
$("#first").load(function() {
var imgheight = $(this).height();
$("#first_papers").css("height", imgheight);
});
});
</script>
This should make it execute whenever your page loads no matter when/how you navigate to it.

why does this jquery image swap not work in chrome and on first load in firefox

I am trying to use jquery to replace an image on rollover (with fade) you can see this on the bottom left here:
http://www.anzie.com/index_rollover.php
However in chrome it just fades to near opaque. and in firefox on the first load I get a small blue box on the top left corner (as if it is out of position). but then on refresh it works in firefox. This is working perfectly on my own machine, it only does not work when I try it online. Which leads me to thing it is not loading the images in time perhaps? I am not sure what to do..
Here is my php:
<img src="images/home_buttons/water_bag.jpg" alt="watch la vie en couleur" border="0" align="left" hoverImg="images/home_buttons/water_bag-hover.jpg" />
And here is the javascript:
<script type="text/javascript">
$(document).ready( function() {
$('body').find('*[hoverImg]').each(function(index){
$this = $(this)
$this.wrap('<div>')
$this.parent().css('width',$this.width())
$this.parent().css('height',$this.height())
$this.parent().css('background-image',"url(" + $this.attr('hoverImg')+")")
$this.hover(function() {
$(this).stop()
$(this).fadeTo('',.01)
},function() {
$(this).stop()
$(this).fadeTo('',1)
})
});
});
</script>
When I right click in chrome and say "Inspect"; your height/width are set to 0px. If I inline edit your height/width via chromes tools the image appears. Try jquery's outerWidth() and see if that provides better results.
http://api.jquery.com/outerWidth/
Try calling your code in
$(document).load( ... )
instead. Images aren't ready in ready. Load is a callback for anything with a src attribute. So once all those load (including images) it will fire. You can also call it on images. For example
$('img').load( function() ... );
Method chaining for performance.
$('body').find('*[hoverImg]').each(function(index){
$this = $(this)
$this.wrap('<div>')
.parent()
.css('width',$this.width())
.css('height',$this.height())
.css('background-image',"url(" + $this.attr('hoverImg')+")")
.end()
.hover(function() {
$(this).stop()
$(this).fadeTo('',.01)
},function() {
$(this).stop()
$(this).fadeTo('',1)
})
});

width returning 0 in jquery

i have some jquery script which runs after the window has loaded
$(window).load( function() {
$('.picture a img').each(function(index) {
$(this).height(280);
if ($(this).width() > $(this).height()) {
alert("yes");
} else {
alert("no");
}
});
});
i always get a "no" from this when i know some of the images should be a "yes". When i trace the script in chrome i noticed that the $(this).width() always returns a 0. ive googled around and some suggestions were that the images havent loaded but here ive used the window.load method which i thought should run once everything has loaded. any ideas??
thanks for any help in advance
Chrome is weird about image widths. I noticed then when building a jQuery photo gallery. If your image width is not specifically set in the tag, chrome will return 0. FF, and IE will figure out the width, but chrome will not. Try actually setting the width and see if you get the desired result then.
<img width="200" src="..." />
You need to run your code when the image is loaded, the following code should work:
$(window).load( function() {
$('.picture a img').load( function() {
$(this).height(280);
if ($(this).width() > $(this).height()) {
alert("yes");
} else {
alert("no");
}
});
});
note that every DOM element that have some kind of web resource associated to (window, img, iframe) respond to .load() event.
try
if ($(this).attr("width") > $(this).attr("height")) {
try adding a load event on the image, so it will only execute when the image is fully loaded.
$(window).load( function() {
$('.picture a img').each(function(index) {
$(this).bind('load', function () {
$(this).height(280);
if ($(this).width() > $(this).height()) {
alert("yes");
} else {
alert("no");
}
})
});
});
you can also try checking this.complete on the image object
I just wanted to add that you should also ensure that your image is actually a visible element. I've had plenty of issues in the past trying to measure visible:hidden or display:none elements. If you are indeed attempting to measure a hidden element, you can get past it by doing something like
var width = $('img').show().width();
$('img').hide();
Now that code is incredibly vague, but it gives you my thought behind visibility flashing.
The correct method to use, to run your scripts after the dom has finished loading, is:
$(document).ready(function() { /*your code here*/ });

Categories