Tom Tom - 1 month ago 7
HTML Question

Try to get two images to resize according to page width

I have two images that I am pulling from a JSON file. Both images scale down accordingly depending on the screen width when the browser is resized, but on page load the initial image doesn't show until the page is resized. Hope someone can help below is my code:



(function() {

'use strict';

var url = 'path to json';

$.getJSON(url, function(json) {

var sliderImage = '';
var categoryImage = '';

$.each(json[0], function (i, item) {
sliderImage += '<img src="' + item.imageSliderURL + '">';
categoryImage += '<img src="' + item.imageCategoryURL + '">';
});

$(window).resize(function() {

if ($(this).width() >= 800) {
$('#recipeSlider').html(sliderImage);
} else if ($(this).width() <= 800) {
$('#recipeSlider').html(categoryImage);
}
});

});
})();

<div id="recipeSlider"></div>




Answer

Here is your answer.

 (function() {

 'use strict';

 var url = 'path to json';

 $.getJSON(url, function(json) {

     var sliderImage = '';
     var categoryImage = '';

     $.each(json[0], function (i, item) {
         sliderImage += '<img src="' + item.imageSliderURL + '">';
         categoryImage += '<img src="' + item.imageCategoryURL + '">';
     });
     function funLoadImage(){

        if ($(this).width() >= 800) {
            $('#recipeSlider').html(sliderImage);
        } else if ($(this).width() <= 800) {
            $('#recipeSlider').html(categoryImage);
        }
     }

     funLoadImage();
     $(window).resize(funLoadImage);

  });
  })();

The problem with your code was it's not assigning image to element when page is loaded for first time.