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

Executing Python script via AJAX or jQuery

I need to execute Python scripts from JavaScript. The goal is to provide an input String to the Python script as an argument and then showcase the output on our webpage. Below is the Python code that runs smoothly on my Linux box: ./sample.py 12345 produc ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

Error: Unable to access properties of an undefined value (trying to read 'type') within Redux Toolkit

Looking for help with this error message. When trying to push the book object into the state array, I encounter an error. Folder structure https://i.stack.imgur.com/9RbEJ.png Snippet from BookSlice import { createSlice } from "@reduxjs/toolkit" const ...

Serialization and deserialization of JSON formats

Having trouble deserializing a JSON payload and not receiving any value after the process. Below is the JSON payload: { "01/01/2010":{ "Frequency":3, "term": 24 }, "01/01/2011":{ "Frequency":6, "term": 12 }, ...

Complete my search input by utilizing ajax

It's only been 30 minutes since my last post, but I feel like I'm making progress with my search posts input: I've developed a model that resembles this: function matchPosts($keyword) { $this->db->get('posts'); ...

Migrate the JavaScript variable created with 'passport' to an Express router

In my quest for authentication, I created the essential passportAuth.js file: module.exports = function(passport, FacebookStrategy, config, mongoose, fbgraph){ passport.serializeUser(function(user,done){ //to make user reference available across pages ...

I am unfamiliar with this specific JavaScript algorithm problem from Codewars

I need help with a JavaScript algorithm question This problem involves extracting two letters from the middle of odd-numbered characters My confusion lies in function getMiddle(s) { //Code goes here! let answer = ""; if (s.length % 2 !== 0) { a ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

Behind the scenes, unable to launch due to Schema Error

My experience with Backstage was going smoothly until I ran into an issue after executing a yarn install this afternoon. Now, whenever I attempt to run yarn dev, it fails with the following error: [0] Loaded config from app-config.yaml [0] <i> [webpa ...

Interpreting the Response from Jquery's GetJson Method

I've been facing the same issue repeatedly; I struggle to read the response from a JSON post. For instance $.getJSON('http://gdata.youtube.com/feeds/api/users/live/subscriptions?alt=json', function(data) { $.each(data.feed.entry, functi ...

Modify the AJAX data in Datatables without directly modifying the elements

I am currently working with a Datatable that is being populated through AJAX, and everything is going smoothly. However, I am looking for a way to include some shortcuts to send requests to the server. The issue lies in how I can modify the data being sent ...

Challenges with the efficiency of the Material UI Datagrid

I am currently using MUI Datagrid to display my records, but I am experiencing delays with my modal and drawer components. Even after attempting to optimize with useMemo for my columns, I have not been able to achieve satisfactory performance. https://i.st ...

How to display logged-in user information on the homepage

Code for multiuser login $scope.users = [ {uname: 'fida', password: 'fida', age:26, department:"science"}, {uname: 'anu', password: 'anu', age:23,department:"maths"}, {uname: 'nida&apo ...

Check the row in a JQuery table by using the .on("click") function to determine if a hyperlink within the row was clicked or if

I am in the process of building a website using the following libraries: Parse.js: 1.4.2 JQuery: 1.11.2 and 1.10.3 (U.I.) Twitter Bootstrap: 3.3.4 To demonstrate what I am trying to achieve, I have set up this JSfiddle with placeholder data: https://jsf ...

Is it possible to have several forms triggered by the same AJAX call but produce varying results

If I have multiple PHP-generated forms and want to include a "Reply" button on each form that sends its content via ajax to another PHP page, can I use the same JavaScript code snippet for all of these elements? <form id="foo"> <label for="ba ...

Retrieving a JSON object based on its name

Here is the structure of a JSON object I am working with: [ { "filters": [ { "name": "category", "list": [ { "category-abc": { "title": "abc", "number": "2" ...

I must first log a variable using console.log, then execute a function on the same line, followed by logging the variable again

Essentially, I have a variable called c1 that is assigned a random hexadecimal value. After printing this to the console, I want to print another hex value without creating a new variable (because I'm feeling lazy). Instead, I intend to achieve this t ...

A static iframe or an alternative solution that is not interactive

I specialize in creating websites for my clients. When they log in, they are presented with 5 different design ideas for their site - each showcasing a unique layout and color scheme. Currently, I manually upload 5 screenshots of the designs created by me ...

Creating a jQuery alertbox that is triggered by specific elements in an anchor tag

I am working on an HTML page that contains 50 A tags. I am trying to figure out how to create an alert based on a specific element inside the A tag. Here is an example of what I am looking for: <a href "something">click to see the alert</a> ...

Error: Unable to locate module during module creation

I encountered an error while trying to import a module in my test application. ../fetchModule/index.js Module not found: Can't resolve './Myfetch' in '/Users/******/nodework/fetchModule' Here is the folder structure: And her ...