Guide on organizing items into rows with 3 columns through iteration

Click on the provided JSFiddle link to view a dropdown menu that filters items into categories. Each item is stored as an object in an array for its respective category. Currently, all items are displayed in one column and I want to divide them into three columns by counting how many items will be displayed for each category.

To accomplish this, I plan on using a for loop to count up to the specified number of items for each category and then distribute them among the columns. The loops will be nested, with the outer loop initiating a new row and the inner loop inserting the correct number of items in each row/column. It may sound a bit complex, but I believe it's doable even though I'm relatively new to jQuery and web programming.

If you have any tips or guidance on how to achieve this task, I would greatly appreciate it! Thank you in advance!

Here is a snippet of my code:

HTML:

<div class="btn-group">
<button id="division-select" class="btn btn-info dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-target=".nav-collapse">Categories<span class="caret"></span></button>
<ul id="filterOptions" class="dropdown-menu">
    <li id="get_cats"><a href="#" class="cats">Cats</a></li>
    <li id="get_dogs"><a href="#" class="dogs">Dogs</a></li>
    <li id="get_birds"><a href="#" class="birds">Birds</a></li>
    <li id="get_all"><a href="#" class="everything">Everything</a></li>
   </ul>
</div> <!-- .btn-group -->  

<div class="row">
    <div class="col-md-4 text-center">
        <a id="cats"></a>
        <a id="dogs"></a>
        <a id="birds"></a>  
        <a id="everything"></a>
    </div>
</div>

JavaScript:

var data={
    "cats":[
        {"breed":"bengal"},
        {"breed":"savannah"},
        {"breed":"ragdoll"},
        {"breed":"munchkin"},
        {"breed":"siamese"}
    ],
    "dogs":[
        {"breed":"german shepherd"},
        {"breed":"jack russell terrier"}
    ],
    "birds":[
        {"breed":"parrot"}
    ],
    "everything":[
        {"breed":"bengal"},
        {"breed":"savannah"},
        {"breed":"ragdoll"},
        {"breed":"munchkin"},
        {"breed":"siamese"},
        {"breed":"german shepherd"},
        {"breed":"jack russell terrier"},
        {"breed":"parrot"}
    ]
}

$( document ).ready(function() {
    everything();
});

$(document).ready(function () {
    $("#get_cats").click(
        function () {
            cats();
        }   
    );   
});

$(document).ready(function () {
    $("#get_dogs").click(
        function () {
            dogs();
        }  
    );   
});

$(document).ready(function () {
    $("#get_birds").click(
        function () {
            birds();
        }   
    );   
});

$(document).ready(function () {
    $("#get_all").click(
        function () {
            everything();
        }  
    );   
});

function cats() {
    document.getElementById("dogs").innerHTML="";
    document.getElementById("birds").innerHTML="";
    document.getElementById("everything").innerHTML=""; 
    var output="<div class='text-center'>";
    for (var i in data.cats) {
        output += "<a class='thumbnail'><h3>"+ data.cats[i].breed +"</h3></a>";
    }
    output+="</div>";
    document.getElementById("cats").innerHTML=output; 
}

function dogs() {
    document.getElementById("cats").innerHTML="";
    document.getElementById("birds").innerHTML="";
    document.getElementById("everything").innerHTML=""; 
    var output="<div class='text-center'>";
    for (var i in data.dogs) {
        output += "<a class='thumbnail'><h3>"+ data.dogs[i].breed +"</h3></a>";
    }
    output+="</div>";
    document.getElementById("dogs").innerHTML=output; 
}

function birds() {
    document.getElementById("dogs").innerHTML="";
    document.getElementById("cats").innerHTML="";
    document.getElementById("everything").innerHTML=""; 
    var output="<div class='text-center'>";
    for (var i in data.birds) {
        output += "<a class='thumbnail'><h3>"+ data.birds[i].breed +"</h3></a>";
    }
    output+="</div>";
    document.getElementById("birds").innerHTML=output; 
}

function everything() {
    document.getElementById("dogs").innerHTML="";
    document.getElementById("birds").innerHTML="";
    document.getElementById("cats").innerHTML="";   
    var output="<div class='text-center'>";
    for (var i in data.everything) {
        output += "<a class='thumbnail'><h3>"+ data.everything[i].breed +"</h3></a>";
    }
    output+="</div>";
    document.getElementById("everything").innerHTML=output; 
}

JSFiddle

Answer №1

Are you interested in displaying sub categories in three columns as opposed to one?

If so, you can achieve this simply through CSS without the need for JavaScript.

<a id="everything"><div class="text-center"><a class="thumbnail"><h3>bengal</h3></a><a class="thumbnail"><h3>savannah</h3></a><a class="thumbnail"><h3>ragdoll</h3></a><a class="thumbnail"><h3>munchkin</h3></a><a class="thumbnail"><h3>siamese</h3></a><a class="thumbnail"><h3>german shepherd</h3></a><a class="thumbnail"><h3>jack russell terrier</h3></a><a class="thumbnail"><h3>parrot</h3></a></div></a>

Instead of using UL > LI, assign a 33% width to LI and float: left;

This should address your question. You can also utilize CSS on the .thumnail class.

Please note that your fiddle link is not producing any output.

.thumbnail {
    width:30%;
    float:left;
    margin:4px;
}
.thumbnail h3 {
    min-height:80px;
}

Click on this link for reference : http://jsfiddle.net/pragneshkaria/BZ63R/4/

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

Speaking about the `this` Vue component in an event listener context

Consider this Vue component that is equipped with a global event listener: let myApp = new Vue({ data: { foo: 0; }, methods: { handle: function(event) { this.foo = 1; // 'this' pertains to the handler, not ...

Error: Unable to access the 'name' property of an undefined variable

When running the code, I encountered a "TypeError: Cannot read property 'name' of undefined" error, even though when I console.log it, it provides me with the object import React from "react"; class Random extends React.Component { constructo ...

Should the article ID be sent to the ajax file, or should the ajax file retrieve the article ID directly? This dilemma arises in a

I am trying to pass the current article ID to an ajax file. The URL of the ajax file is something like www.web.com/plugins/system/ajax.php, so using JRequest::getInt(id) always returns 0 integer. However, in a non-ajax file, I can get the ID the same way. ...

Guide on integrating materialize-css npm package into webpack

I'm currently developing a client-side application with Webpack and facing challenges when trying to incorporate the materialize-css package. Using Henrik Joreteg's hjs-webpack package, I was able to include the yeticss npm package by importing i ...

The onChange event was not able to be activated within the material-ui radioGroup component

Utilizing the RadioButton component to showcase different options of a question within a custom-built component: import FormControl from "@material-ui/core/FormControl"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Grid from " ...

Can you explain what JSX is, its purpose, and the benefits of using it?

As I delve into the world of React, I can't escape the constant mention of JSX. Despite my efforts to grasp it by watching tutorials, the concept still eludes me. Even after consulting the documentation, my mind remains in a state of confusion. To m ...

Conceal the iframe if the source is http:// and there is no associated

Is there a way to hide the iframe only if the src starts with "http://"? This is what I have tried so far: <script type="text/javascript> if ( $('iframe[src^="http://"]') ) document.getElementById('iframe').style.d ...

Is there a way to ensure all images have uniform height using CSS?

I manage a dating platform where I showcase user profiles along with their profile pictures. In case a user doesn't have a profile picture, I show a specific default image. Below is the code snippet: @register.inclusion_tag(filename='accounts/pr ...

Unusual Methods in Vue.js: Exploring Odd Behavior

In my application, I have a single data variable called message, as well as a method in the methods section that performs cryptographic algorithms. Below is the code snippet: export default { data: () => ({ message: "" }), methods: { clic ...

Tips for Enhancing the Appearance of a List Input Box

While on my hunt for an auto-completing text field, I stumbled across lists. <label>Bad Habit <input list="badhabits" id="habits" name="habit"/> </label> <datalist id="badhabits"> <option value="alcoholics"> <option ...

A captivating opportunity for a web developer specializing in frontend design

Encountered an intriguing dilemma that has me stumped. There is a single stipulation: Only the json can be altered! I am struggling to meet this requirement: data.hasOwnProperty("\u{0030}") class JobHunter { get data() { return &ap ...

What is the best way to include the ID in a Vue.js Ajax request for posts?

Is there a way to pass an "id" obtained as data in vue js? The id is coming as "agnt.basic.actor". Considering the presence of multiple ids, how can I achieve this? <tr v-for="agnt in agentlist"> <td v-if="agnt.basic">{{agnt.basic.actor}}< ...

My experience with jquery addClass and removeClass functions has not been as smooth as I had hoped

I have a series of tables each separated by div tags. Whenever a user clicks on a letter, I want to display only the relevant div tag contents. This can be achieved using the following jQuery code: $(".expand_button").on("click", function() { $(th ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

Eliminate operation in React with the help of Axios

Within my React application, I have implemented a callback method for deleting data from an API using the axios library: deleteBook(selectedBook) { this.setState({selectedBook:selectedBook}) axios.delete(this.apiBooks + '/' + this.select ...

Addressing the Cross Domain Issue when Implementing DHIS 2 API with jQuery

Today, I spent hours trying to authenticate my javascript application with the DHIS 2 API using Jquery. According to the API documentation (https://www.dhis2.org/doc/snapshot/en/user/html/ch32s02.html), base 64 authentication is required. However, my attem ...

Utilize a standard JavaScript function from a separate document within a function of a React component

I am facing an issue where I need to incorporate a standard JavaScript function within a React component function. The script tags are arranged in the footer in the following order: <script src="NORMAL JAVASCRIPT STUFF"></script> // function ...

Having trouble obtaining a GuildMember's displayName in Discord.js leads to a TypeError

I'm completely baffled by the situation here. My code is integrated within the Akairo Framework, yet the error seems to be pointing fingers at discord.js itself. Take a look at the error message below: /home/runner/guard/Listeners/automod/nicknames.js ...

Cross Domain Requests in Internet Explorer: Preflight not being sent

I have come across several similar discussions but none of the solutions provided have worked for me so far. Issue: In our current setup, we have three servers hosting our http-apis - two for testing and one for production. Lately, we have been deployin ...