Use jQuery to get the "true size" of the image without deleting the class

I use Jcrop on an image that changes using CSS for consistency.

Js

<script type="text/javascript"> $(window).load(function() { //invoke Jcrop API and set options var api = $.Jcrop('#image', { onSelect: storeCoords, trueSize: [w, h] }); api.disable(); //disable until ready to use //enable the Jcrop on crop button click $('#crop').click(function() { api.enable(); }); }); function storeCoords(c) { $('#X').val(cx); $('#Y').val(cy); $('#W').val(cw); $('#H').val(ch); }; </script> 

HTML

 <body> <img src="/path/to/image.jpg" id="image" class="img_class" alt="" /> <br /> <span id="crop" class="button">Crop Photo</span> <span id="#X" class="hidden"></span> <span id="#Y" class="hidden"></span> <span id="#W" class="hidden"></span> <span id="#H" class="hidden"></span> </body> 

CSS

 body { font-size: 13px; width: 500px; height: 500px; } .image { width: 200px; height: 300px; } .hidden { display: none; } 

I need to set the variables h and w to the size of the actual image. I tried using the .clone() manipulator to make a copy of the image and then remove the class from the clone to get the size, but it sets the variables to zeros.

 var pic = $('#image').clone(); pic.removeClass('image'); var h = pic.height(); var w = pic.width(); 

It works if I add an image to a page element, but these are large images, and I would prefer not to upload them as hidden images if there is a better way to do this. Also, deleting the class, setting the variables, and then re-adding the class caused sporadic results.

I was hoping for something like:

 $('#image').removeClass('image', function() { h = $(this).height(); w = $(this).width(); }).addClass('image'); 

But the removeClass function removeClass not work like this: P

+4
source share
2 answers

Try to hide the image, then take the dimensions and show it:

 var $img = $("#image"); $img.hide().removeClass("image"); var width = $img.width(); var height = $img.height(); $img.addClass("image").show(); 

This should eliminate any weird behavior you might see when adding and removing a class.

+4
source

Perhaps you can clone an image (it should not be extremely painful on the network because it needs to be cached) and get the size of the cloned:

 $newImg = $("#image").clone(); $newImg.css("display", "none").removeClass("image").appendTo("body"); var width = $newImg.width(), height = $newImg.height(); $newImg.remove(); 

Good luck

+1
source

Source: https://habr.com/ru/post/1334724/


All Articles