Organize a series of <span> elements into rows and columns through the use of CSS, JavaScript, or jQuery

Task: Your challenge is to display a list of span elements in both vertical and horizontal layouts without altering the HTML structure.

Input: an unknown number of span elements within a parent span like the example below:

<span id="parent">
<span id="child-1">1</span>
<span id="child-2">2</span>
<span id="child-3">3</span>
<span id="child-4">4</span>
<span id="child-5">5</span>
<span id="child-6">6</span>
<span id="child-7">7</span>
<span id="child-8">8</span>
<span id="child-9">9</span>
<span id="child-10">10</span>
...
...
...
</span>

Output: Using CSS classes and JavaScript/jQuery, arrange the child-spans in N rows and M columns as specified. The number of rows (N) and columns (M) will vary, so adding additional HTML elements within the parent span is not allowed.

For example, if you have 12 child-spans and N=4 and M=3:

Horizontal order:

1 2 3
4 5 6
7 8 9
10 11 12

Vertical order:

1 5 9
2 6 10
3 7 11
4 8 12

Good luck with the challenge!

Answer №1

To start, ensure that the inner spans have their float style set to "left" within a static style block. Additionally, assign them a constant width to ensure they can fit within columns.

<style type="text/css>
    #parent span { float: left; display: block; width: 100px; }
</style>

Next, use JavaScript to rearrange the spans by appending them back to the parent element in the correct order. Modify the clear style dynamically to separate rows. Here is an example code snippet:

function arrangeInHorizontalOrder(rows, cols)
{
    var parent = document.getElementById("parent");
    for (var row = 0; row < rows; ++row)
    {
        for (var col = 0; col < cols; ++col)
        {
            var index = 1 + col + row * cols;
            var span = document.getElementById("child-" + index);
            if (span)
            {
                span.style.clear = col ? "none" : "left";
                parent.appendChild(span);
            }
        }
    }
}

function arrangeInVerticalOrder(rows, cols)
{
    var parent = document.getElementById("parent");
    for (var row = 0; row < rows; ++row)
    {
        for (var col = 0; col < cols; ++col)
        {
            var index = 1 + row + col * rows;
            var span = document.getElementById("child-" + index);
            if (span)
            {
                span.style.clear = col ? "none" : "left";
                parent.appendChild(span);
            }
        }
    }
}

Keep in mind that the only difference between the two functions lies in the index calculation.

Answer №2

To achieve the desired column layout, the CSS styling is used for the columns, while the order of the columns can be manipulated using JavaScript.

Each span element is given a fixed width, and then the parent span is assigned a fixed width that accommodates the specified number of columns.

<style type="text/css">
#parent {
  display: block;
  width: 5em;
  border: 1px solid red
}

#parent span {
  width: 1.3em;
  border: 1px solid blue;
}
</style>

<span id="parent">
  <span id="0">0</span>
  <span id="1">1</span>
  <span id="2">2</span>
  <span id="3">3</span>
  <span id="4">4</span>
  <span id="5">5</span>
  <span id="6">6</span>
  <span id="7">7</span>
  <span id="8">8</span>
  <span id="9">9</span>
  <span id="10">10</span>
  <span id="11">11</span>
</span>

Answer №3

Here is a simple solution for aligning items horizontally:

$('#parent').css('text-align','left').children().each(function(i){if((i+1)%3==0) $(this).after('<br>')})

However, we are still in search of an alternative solution for arranging items vertically...

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

Using Selenium to trigger a click event on an ng-click directive in AngularJS is not functioning properly

I am currently trying to confirm that a specific external function is being called when an ng-click event occurs. The code for the input declaration is shown below. While everything seems to be functioning properly in browsers, I am encountering issues dur ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

Tips for repairing the gray margins on the right and left sides of a webpage

Currently utilizing Bootstrap 5 and incorporating columns within the framework. However, encountering an issue where there is black space on the right side of the screen and certain content disappearing on the left side as demonstrated here. Here is the c ...

The execution of jQuery Ajax requests with "when" is encountering issues

My goal is to initiate 8 ajax GET requests N number of times, and this is the code I have written: var me = this; urls.forEach(function(requests){ $.when(requests.map(function(request){ return $.ajax(request) })).done(function(data){ me.result ...

Step-by-step guide on implementing a border-bottom for an active link

Is there a way to apply a border-bottom to btn_articles and btn_posts when one of them is clicked? I attempted to use the active class but it did not have the desired effect. Any suggestions or solutions would be greatly appreciated. let btn_articles = ...

What is the process for invoking a JavaScript function from the code-behind of an Asp.Net application?

Here is a sample of my JavaScript function : function NeedToExport() { alert('Time to export your data!'); } Additionally, in my ASP.NET code behind : Page.ClientScript.RegisterStartupScript(this.GetType(), "ExportKey", "NeedToExport();"); ...

What is the best way to duplicate a Typescript class object while making changes to specific properties?

I have a Typescript cat class: class Kitty { constructor( public name: string, public age: number, public color: string ) {} } const mittens = new Kitty('Mittens', 5, 'gray') Now I want to create a clone of the inst ...

Leveraging Multiple MongoDB Databases in Meteor.js

Can 2 Meteor.Collections fetch data from separate MongoDB database servers? Dogs = Meteor.Collection('dogs') // mongodb://192.168.1.123:27017/dogs Cats = Meteor.Collection('cats') // mongodb://192.168.1.124:27017/cats ...

Creating Header Images for Websites, like the way Facebook does

Exploring how to properly configure the header image on my website has been intriguing. The main issue is that when I view it on my laptop, which has a width resolution of around 1280px, the header image's width measures about 2000px. My goal is to h ...

Need to conceal certain images in Isotope, but ensure they can easily be revealed when necessary?

I have a collection of various images on my website coded with isotope. My question is, how can I hide specific images that I don't want to display initially, but have them appear when needed? I have managed to create a "show all" list using the code ...

What is the best way to display jQuery/AJAX response in a table cell?

I am struggling with a script that retrieves data from a SQL database query and need help placing the result in a specific table cell. Here is the query: <script type="text/javascript"> $(document).ready(function(){ $('.typeval').change(f ...

What could be causing my hamburger icon to malfunction?

https://codepen.io/anon/pen/QNqgMo Curious why the top line of the animation isn't moving. Any code wizards out there who can spot the mistake? Appreciate it! #hamburger-icon.active .line-1 { transform: translateY(25px) translateX(0) rotate(45deg); ...

Navigating the process of returning a list from an AJAX method to a view through a controller in ASP.NET MVC

I need to retrieve a list from my controller and pass it to the view. Currently, I have the following script: function fetchNames(_id, _name) { $.ajax({ type: 'Post', url: 'GetNames/', data: { id: _id, name: _name}, su ...

Angular utilizes ZoneAwarePromise rather than a plain String output

I expected the giver code to return a string, but it is returning ZoneAwarePromise. Within the service: getCoveredPeriod() { let loanDetails = this.getLoanDetails().toPromise(); loanDetails.then((res: any) => { const coveredPeriodStart ...

Is it possible to distinguish and identify each separate window when a user opens multiple instances of your site?

Has anyone explored the possibility of distinguishing between multiple windows a user may open on the same site? My goal is to assign the initial window the name "window1" and subsequent windows "window2" and so forth. Is there a method for achieving this ...

Leverage HTML within JSON for a multilingual website using i18next with Next.js

I am working on a multi-language website using Next.js. To handle the translations, I am using the package i18next. In my JSX code, I define variables like this: {t("satisfied:title")} This means {t("JSONfileName:JSONvariable")} However, when I try to i ...

Unusual thin border of white pixels on IE 9

Having some issues with border radius in IE-9. The left border is showing white pixels. Any thoughts on why? This problem is only in IE 9, other browsers look fine. Here is the code snippet: <ul class="tags clearfix"> ...

Transform object into JSON format

Is there a way to transform an object into JSON and display it on an HTML page? let userInfo = { firstName: "O", lastName: "K", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b44476b445b05484446">[ema ...

Not every situation calls for the same type of styling

I am struggling to override the CSS for <h1> and <h2> using specific selectors only. The changes are only being applied to one class, with <h1> changing color to green but not <h2>. Can someone please assist me in identifying where ...

HTML/ModX styling for selected textboxes

I am looking to enhance the style of my search-box, which is similar to the one on THIS website. While I have tried using :active, the effect only lasts for a brief moment. Currently, my code is heavily influenced by modX terms, but I will still share it h ...