Customizing Images using a JSON array of images

Looking to implement a feature that displays images fetched from a CMS via a JSON file.

The JSON data structure is as follows:

{  
 "images": [
  {"title": "Image One", "url": "image1.jpg"},
  {"title": "Image Two", "url": "image2.jpg"},
  {"title": "Image Three", "url": "image3.jpg"},
  {"title": "Image Four", "url": "image4.jpg"},
  {"title": "Image Five", "url": "image5.jpg"}
 ]
}

The corresponding HTML snippet is:

<ul id="mylist"></ul>

The number of images varies and can be 3, 4, or 5. The layout specifications are as follows:

  • If there are three images, each image should take up 33% of the width
  • If there are four images, they should be displayed in two rows, with each image occupying 50% of the width
  • If there are five images, the top row should contain three images with each taking up 33%, while the second row should have the remaining two images distributed equally with 33% width each

Seeking assistance on achieving this using JavaScript, jQuery, Mustache, or similar technologies. Any help would be appreciated!

Answer №1

If you find yourself dealing with an even number of images, opt for two columns. But if the number is odd, three columns would work better.

Calculating the number of rows is straightforward once the number of columns is determined; simply divide and round up to get the result.

var numb = obj.images.length;

var cols = numb % 2 === 0 ? 2 : 3;
var rows = Math.ceil(numb / cols);

FIDDLE

To adjust this setup to widths instead, follow these steps:

var numb = obj.images.length;

var width = numb % 2 === 0 ? '50%' : '33%';

$('.images').css('width', width)

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

Parsing HTML with AngleSharp - Extracting Text from IElement

I am currently developing an HTML parser using AngleSharp that takes input in the following format: <p> Paragraph Text <a href="https://www.example com" class="external text" target="_new" rel="nofollow">Link Text</a> Paragraph Text 2 &l ...

Tips on switching the positions of two links when they are clicked using jQuery

<div class="applications-wrapper"> <div class="eye" id="onetwo"><a class="fa fa-eye" href="#"></a></div> <div class="bar" id="twothree"><a class="fa fa-bars" href="#"></a></div> </div> My ...

Enhance nested models within a Rails API

I am interested in constructing a Rails API that can create nested records within the database. My goal is to send data to the database for a model associated with a has_many relationship. Is this the correct approach, or are there alternative methods for ...

How can Angular HttpClient be used to convert from Http: JSON.parse(JSON.stringify(data))._body?

When using the Http module, you can use this method: Http service: let apiUrl = this.apiUrl + 'login'; let headers = new Headers({'Content-Type': 'application/json'}); return this.http.post(apiUrl, JSON.stringify(model), {h ...

Harnessing Spread Syntax with Map and Filter Operations

Recently stumbled upon a fascinating problem that I couldn't wait to share with all of you. Here is the question at hand: [...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7] I managed to successfully solve the initial section up to the fi ...

HTML5 Division Element Dimensions

I am currently modifying an HTML5 template. The default Bootstrap parameters were set as: col-sm-12 col-md-4 col-lg-4 col-sm-12 col-md-8 col-lg-8 This configuration allotted 20% of the screen width to text and 80% to images, but I want it reversed. Tex ...

Converting Hibernate Set to JSON format

public Class B { @Column private String name; private Set<A> values; @ManyToMany(fetch = FetchType.EAGER) @Fetch(FetchMode.JOIN) public Set<A> getValues() {//manytomany return values; } public void setValue ...

jqgrid's date restriction is set to November 30th, 1999 at midnight

I have a table displaying DATETIME values. However, after editing the datetime value, it always changes to "1999-11-30 00:00:00", both in jqgrid and the database, regardless of the date entered. [Tue Mar 12 11:39:28 2013] [error] [client 171.43.1.4] PHP N ...

Is jQuery the solution for tidying up messy HTML code?

Is there a way to clean up this markup using jQuery? <span style="font-size:19px"> <span style="font-size:20px"> <span style="font-size:21px"> Something </span> </span> </span> I'm looking to tra ...

Troubleshooting: Discord bot failing to initialize on Heroku

After successfully hosting my bot on Heroku for a while, I temporarily switched back to self-hosting to update to discord.js v13. Now that I'm done with the updates and trying to re-host the bot on Heroku, I'm encountering this error: (node:4) Un ...

Dropdown menu will appear when you click on one of the menu items

Can someone help me create a dropdown menu using a JavaScript function that toggles on click? I've attempted to do so with the following code, but it's not working as expected. Could you please point out where I might be going wrong? I'm loo ...

Is there a way to refresh autocomplete/autofill after form submission with a custom JavaScript function?

I've developed a Vue application that includes a form. Once the user clicks on submit, an Ajax request is made using Axios through a JavaScript function. The data being sent is a custom JSON object that I have constructed by combining the information ...

How to create an array of objects using an object

I have a specific object structure: { name: 'ABC', age: 12, timing: '2021-12-30T11:12:34.033Z' } My goal is to create an array of objects for each key in the above object, formatted like this: [ { fieldName: 'nam ...

What steps can I take to resolve a memory issue in node.js?

I encountered the following issue. It appears that the json file is too large to handle due to insufficient server memory. Is there a way to resolve this problem? I've heard about Node streaming, but I find it quite complex. Can you simplify the expl ...

Select element's width decreases by 2 pixels following the application of width adjustment via jQuery

After browsing through numerous pages, I finally managed to adjust the width of my textbox and select element using jQuery 2.0. Snippet of Code from my Project: $(document).ready(function(){ $("#Text2").css('width','20 ...

Is there a way to eliminate this from the footer section?

Check out my website: If the text is not visible, try using a larger monitor or zooming out in your browser. I've added an image to help explain: I only want to remove that element + title on the first page This is the HTML code: <div id="to ...

How to Call a Nested Object in JavaScript Dynamically?

var myObj = { bar_foo : "test", bar : { foo : "hi there"; }, foo : { bar : { foo: "and here we go!" } } } How can we achieve the following: var arr = [["bar", "foo"], ...

Creating a filter using radio input in HTML and CSS is a simple and

Currently, I am delving into the world of Javascript and React, but I have hit a roadblock. My goal is to create a Pokedex, yet I am encountering some difficulties. I have implemented Radio Inputs to filter Pokemon by generation, but I am struggling with ...

Loading views and controllers on-the-fly in AngularJS

A new configuration tool is under development using Angular.JS. The user interface consists of two main sections: a left panel with a tree view listing all the configuration items and a right panel displaying screens for editing these items. There are appr ...

how to use jQuery to locate the immediately preceding node that meets specific criteria

How can I locate the nearest parent node above $(this) node that has a specific property such as class="field", without considering parent/child relationships? ...