I want to transfer the values ​​of the height and width of the loaded image. Before that I tried to do this with the help of return, but I found out that this was not working and was wrong. After decided to do using the callback function. But the question was - how to convey the values ​​of height and width?

As I tried to get the values ​​using return without callback:

popup: { dimentions: {}, testFunc: function testFunc(url) { this.dimentions = this.getMeta(url); console.log(this.dimentions); //browser returns {} h: 1920 w: 720 console.log(this.dimentions.w); //browser returns undefined }, getMeta: function getMeta(url){ var meta = {}; var img = new Image(); img.onload = function(){ meta.w = this.width; meta.h = this.height; }; img.src = url; return meta; //browser returns {} h: 1920 w: 720 }, } 

How I want to do this using callback, but I don’t know how to get the values:

 testFunc: function testFunc(url) { this.getMeta(url, function() { this.dimensions = .... //how can i find dimensions from a callback function? }); console.log("console log: " + this.dimentions); }, getMeta: function getMeta(url, cb){ var meta = {}; var img = new Image(); img.onload = cb; img.src = url; }, 

    2 answers 2

     dimensions: {}, getMeta: function getMeta(url){ var meta = this.dimensions; var img = new Image(); img.onload = function(){ meta.w = this.width; meta.h = this.height; }; img.src = url; }, 

     var img = new Image(); document.body.appendChild(img); img.onload = function() { console.log("In onload: " + img.width + " x " + img.height); } img.src = "https://assets.pernod-ricard.com/uk/media_images/test.jpg"; console.log("Immediately (picture hasn't arrived yet): " + img.width + " x " + img.height); 

    • Still undefined - Evgeny Arkhipov
    • What is "undefined"? - Igor

    Decided so:

     resizePopup: function resizePopup(url) { this.getMeta(url, function(){ ratio = gallery.popup.dimentions.w / gallery.popup.dimentions.h; if(ratio <= 1) { //console.log("console.log: " + popupWidth); content_height = $(".popup-item").height(); content_width = content_height*ratio; $(".popup-item").width(content_width + "px"); } else { } }); }, getMeta: function getMeta(url, cb){ //var meta = {}; //meta = this.dimentions; var img = new Image(); img.onload = function() { gallery.popup.dimentions.w = this.width; gallery.popup.dimentions.h = this.height; cb(); } img.src = url; }, },