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

Discover the hyperlink and submit it via the form to the designated email address

Is it possible to create a basic HTML form that captures name and email details, then uses jQuery to locate a specific link on the page and includes this link along with the form information in a submission to a web server? From there, a script could send ...

Guide on aligning a popup next to the button that activated it using CSS and JavaScript

I am currently generating a dynamic quantity of divs, each containing a button that triggers a popup when clicked. I am attempting to position the popup below the specific button that activated it, but it remains static and does not move accordingly. <d ...

Calculating the total price of items in a shopping cart by multiplying them with the quantity in Vue.js

I am currently working on enhancing the cart system in Vue.js, with a focus on displaying the total sum of product prices calculated by multiplying the price with the quantity. In my previous experience working with PHP, I achieved this calculation using ...

Creating a standard login.js file for seamless integration with nightwatch.js testing

When creating tests for my web application, I need to first simulate a login before proceeding with the rest of the tests to access inner pages. Currently, I am in the process of refactoring the code so that I can create an 'include' for common f ...

Intersecting Hyperlink Elements Creating a Hover Effect

I've encountered a perplexing CSS display issue and I'm at a loss for alternative solutions besides simply widening the width of the parent div. Allow me to explain the layout: <div> <ul> <li> <a href="javascrip ...

Template not rendering array data correctly in Meteor

Here is an example of the array structure: var myarray = [ device1: [ name:device1 , variables: [ variable1: [ name: variable1, unit: "a unit", ...

What is the best way to crop a page?

Running a React application, I am integrating a page from an external ASP.NET app. To achieve my goal of extracting only a section of the page rather than the entire content, I am unsure if it is feasible. Specifically, I aim to extract just the body of th ...

What is the code to position the brand name to the right of a logo in HTML?

As I work on building my webpage, I am facing an issue where I want the brand name to appear directly next to the logo, on the right side. I have attempted to use the float-left property without success. I've included both the HTML and CSS code here. ...

Using PhoneGap to load JSON data with the File API when clicking an event

I have successfully developed code that loads JSON data from an external file on the device. The program is designed to work as follows: Upon a click event, it will first attempt to access the local storage file (course.txt) and if it exists, it will read ...

The backspace key is unresponsive following the use of a jQuery class

Using a specific class for an input field: Here is the code for the input field: <?php echo $this->Form->input('duration', array('class'=>'input-large text-right number-field','value'=>'0&apo ...

scrolling smoothly to a specific div on another webpage

Incorporating a smooth scrolling feature on my website's menu bar has been quite challenging. Specifically, I want the page to redirect to another HTML page and smoothly scroll to a specific div when a sub-item is clicked. To achieve smooth scrolling ...

Arrange a variety of images with different dimensions in a narrow row while keeping the width fixed and adjusting the height accordingly

Imagine you have a collection of 3 (or more) images, each with different sizes and aspect ratios, within a fixed-width div (for example width:100%): <div class="image-row"> <img src="1.png"> <img src="2.png"> <img src="3.png" ...

Save the outcome of an ArrayBuffer variable into an array within a Javascript code

I'm in the process of developing an offline music player using the HTML5 FileReader and File API, complete with a basic playlist feature. One challenge I'm facing is how to store multiple selected files as an ArrayBuffer into a regular array for ...

Can someone provide guidance on creating a JavaScript function that locates an image within an <li> element and sets that image as the background-image property in the li's CSS?

Let's dive deeper into this concept: <li class="whatever"> <img src="/images/clients/something.jpg"> </li> <li class="whatever"> <img src="/images/clients/whatever.png"> </li> He ...

Error: The function gethostname has not been declared

I attempted to set a variable using gethostname() (1) and with $_SERVER(2), but I always receive an error message saying ReferenceError: gethostname is not defined. My goal is simply to fetch the current system name into a variable using JavaScript within ...

Utilizing Yii to Partially Render and Send JSON Response via AJAX

My current issue is regarding the return of data. When attempting to send the rendered partial view data from my controller to AJAX, the code provided below will be utilized. JQuery AJAX: $.ajax({ url: "<?php echo $this->createUrl('aj ...

After fetching, null is returned; however, refreshing the page results in the object being returned. What is the

I have a specific case where I am dealing with an array of 500 post IDs and I need to retrieve the first 100 posts. To achieve this, I implemented the following code: API https://github.com/HackerNews/API BASE_URL = 'https://hacker-news.firebaseio.com ...

Require assistance with understanding the aes-256-cbc encryption using oaepHash

Procedure for Secure Data Encryption: Generate a random 256-bit encryption key (K_s). For each Personally Identifiable Information (PII) value in the payload: 1. Pad the plaintext with PKCS#7 padding. 2. Create a random 128-bit Initialization Vector (IV). ...

Add the hue value from Hue into the Chromajs HSL state value

My objective is to dynamically change the background color of a div based on user input. I plan to assign the user's input as the value of the state key hue, and then set another state key called color to hold the HSL representation of the hue using C ...

Assist me in temporarily altering the color of menu items in a sequential manner upon the page's loading

Currently, I'm working on a website that features a subtle dark grey menu at the top of every page. The menu is built using HTML and CSS with a list structure. To highlight the corresponding menu item based on the current page, I am utilizing the ID a ...