Having trouble with styling images pulled from a JSON file and displayed on an HTML page

Sorry for the confusion - my webpage is displaying images, but the CSS styling is not being applied to any of them. I've tried adding a class, inline styling in the HTML (with style=""), and using jQuery's .addClass or .css, but none of these methods are working.

Here is the HTML where the images are being displayed:

<div class="Hats2">

</div>

And here is the jQuery code I am using to display the images:

$(function() {

    var products = []

    $.getJSON('test.json', function(data) {
        $.each(data.products, function(i, f) {
            var tblRow = '<div class="Hats"><img src=' + f.imUrl + '></div>'
            $(tblRow).appendTo(".Hats2");
        })
    })
})

I also have three lines of CSS that try to change the size of the images under the class 'Hats'. I've applied this class to both the img element itself and the div it's in (like it is now).

.Hats {
    width: 200px;
    height: 200px;
}

But no matter what I try, the CSS doesn't seem to have any effect. I've attempted different stylings like border-radius, but nothing works. Could it be because I'm assigning the class through jQuery? I'm really confused about why the styling isn't working. Here is my json file in case that helps:

{ "products": [
{
  "title": "Hat",
  "imUrl": "http://ecx.images-amazon.com/images/I/41pRaO7fFSL._SX395_.jpg"
},
{
  "title": "Hat2",
  "imUrl": "http://ecx.images-amazon.com/images/I/41z9Fhv41lL._SY300_.jpg"
},
{
  "title": "Hat3",
  "imUrl": "http://ecx.images-amazon.com/images/I/41y-UNn0QLL._SX342_.jpg"
}
]
}

Answer №1

The issue lies in the fact that although the .Hats divs are styled correctly to be 200x200px as specified in the CSS, the images you are placing inside of them are larger in size.

https://i.sstatic.net/TnHJl.png

Despite being children of the .Hats divs, the images exceed the boundaries of their parent containers.

To resolve this, simply include the following css rule:

.Hats > img {
  max-width: 100%;
  max-height: 100%;
}

This will help the images fit within their respective parent divs.

var data = {
  "products": [
    {
      "title": "Hat",
      "imUrl": "http://ecx.images-amazon.com/images/I/41pRaO7fFSL._SX395_.jpg"
    },
    {
      "title": "Hat2",
      "imUrl": "http://ecx.images-amazon.com/images/I/41z9Fhv41lL._SY300_.jpg"
    },
    {
      "title": "Hat3",
      "imUrl": "http://ecx.images-amazon.com/images/I/41y-UNn0QLL._SX342_.jpg"
    }
  ]
};

$(document).ready(function() {
  $.each(data.products, function(i, f) {
    var tblRow = '<div class="Hats"><img src="' + f.imUrl + '"></div>';
    $(tblRow).appendTo(".Hats2");
  });
});
.Hats {
    width: 200px;
    height: 200px;
}

.Hats > img {
  max-width: 100%;
  max-height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="Hats2">

</div>

Answer №2

It seems like this solution is not effective.

$(tblRow).appendTo(".Hats2");

The correct way to do it is to use

$(tblRow).appendTo($(".Hats2"));

Answer №3

It is recommended to assign the Hats class to each image element instead, as shown below:

$(function() {

var products = []

$.getJSON('test.json', function(data) {
    $.each(data.products, function(i, f) {
        var tblRow = '<div><img class="Hats" src=' + f.imUrl + '></div>'
        $(tblRow).appendTo(".Hats2");
    })
    $(".Hats").css({width: "200px", height: "200px"});
});

})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Introducing Vee Validate 3.x and the ValidationFlags data type definition

I'm currently struggling to locate and utilize the ValidationFlags type within Vee-Validate 3. Despite my efforts, I am encountering difficulties in importing it. I am aware that this type is present in the source code located here. However, when I a ...

The Vue ChartJS fails to display properly after the page is refreshed

Although this issue may appear to be a common one, some of the suggested solutions are outdated or no longer functional. My objective is to ensure that the chart remains responsive even after the page reloads. I attempted to implement the solution provided ...

The fetch method in Express.js resulted in an error 404 because the requested URL could not be found

Having trouble locating the URL when trying to fetch data for a POST request. I want to mention that my code is written in node.js and express.js. The error message being generated: const form = document.querySelector('form'); form.addEventList ...

BackboneJS struggles to redirect to .fail when an API request exceeds the timeout

I'm a newbie to backbone and I've come across some interesting code that adds Deferred to enable the use of promises. Take a look at the snippet below: getPatientInfo: function fetch(options) { var deferred = $.Deferred(); Backbone.Model.p ...

What is the maximum size allowed for a JSON in the request body when using the post method?

Is there a maximum size limit for a json when it is included in the request body? I've searched for specific information but haven't found any clear answers. ...

Trouble with smooth shading on OBJ file when loaded into Three.js environment

It's interesting how the OBJ appears smooth in my 3D modeling software but looks somewhat quirky and triangular in the Three.js scene. I've applied MeshLambertMaterial to it, which supposedly uses THREE.SmoothShading as its default shading. Despi ...

Utilizing Browserify routes and configuring Webstorm

When building my project using gulp and browserify, I made use of path resolution for easier navigation. By following this guide, I configured browserify as shown below: var b = browserify('./app', {paths: ['./node_modules','./src ...

Ways to activate a function for jQuery selectable list items

I've been working on a code to implement selectable buttons similar to the demo on jquery ui(http://jqueryui.com/selectable/). I'm trying to trigger a function whenever an item is selected (Item 1, Item 2, etc). I've tried multiple approache ...

Exploring React's State Management with useState

Having some trouble with my introductory React Use State practice, specifically when trying to implement a counter and a button for generating random user numbers Check out the code below: import React, { useState } from 'react' import './A ...

Is there a way to obtain the ID number of this specific text view?

Is there a way to access the text of a specific textView in Android? I'm facing an issue where clicking on an ID number always displays '1' in the textView of the next class. This is using JSON array data, which makes it challenging for me a ...

Resetting an Angular Material select component

I've encountered an issue with Angular Material. Currently, I have a form with two select elements. The problem arises when I choose a value in one of the selects, it resets and loses its value. Could this be a bug? Or am I possibly making a mistake ...

Unable to input text by clicking using FabricJS combined with React and Jquery

I am currently working on a project using react and FabricJs. My goal is to add text to the fabricJS canvas by clicking on a button using jQuery. This is the code I have so far: import React, {Component} from 'react' import {fabric} from ' ...

The use of fs.writeFileSync is invalid and will not work for this operation

Encountering an issue while working with fs in next.js, receiving the following error message: TypeError: fs.writeFileSync is not a function Here's a snippet from my package.json: resolve: { fallback: { "fs": false }, } ...

Utilizing Angular 2 for Integration of Google Calendar API

I recently attempted to integrate the Google Calendar API with Angular 2 in order to display upcoming events on a web application I am developing. Following the Google Calendar JavaScript quick-start tutorial, I successfully managed to set up the API, inse ...

Unpacking a container containing interconnected objects

Creating a command line two-player chess game has been an exciting challenge for me. I've structured it with a class for each type of chess piece and a main board class, which is outlined below: class Board attr_accessor :board, :choice def init ...

Integrating Python with MySQL and HTML

My project involves reading data from a GSM modem and storing it in a MySQL database using a Python script. Now, I want to create a front end for this process using an HTML file with a specific design in mind. The Python script acts as the backend in t ...

Unexpected TypeError thrown by a simple react-cube-navigation demonstration

Looking to utilize the react-cube-navigation component, available here. Encountering a TypeError when attempting to run the provided example, React throws an error: TypeError: props.rotateY.to(function (x) { return "scale is not a function. ( ...

Ways to avoid an infinite loop caused by onAuthStateChanged Firebase Authentication

I have a provider setup that initializes the authentication context from Firebase Auth. Everything is working well, but when I tried to introduce persistence by adding an observer with onAuthStateChanged, it caused an infinite loop. Despite including an u ...

Struggling with the installation of SimpLESS

I encountered an issue while attempting to install SimpLESS on my Windows 7 64bit PC. Upon running the installer, I was met with an error message stating: "Could not query info: Invalid HTTP Status Code (403)". Despite my efforts to search for a solution o ...

Convert date from spring to web as a timestamp with Jakson

Looking to extract the timestamp from the "Date start" field in my Match class. I am utilizing Spring, AngularJs, and jackson for JSON conversion. This is how my Spring Controller looks: @RequestMapping(value = "/web2/getMatch", method =RequestMethod.PO ...