Spot the columns generated by CSS and incorporate a new column using JavaScript

Exploring a column newspaper-like layout has led me to wonder if there is a way to use CSS or JavaScript to identify columns (or column breaks) and dynamically insert content between them with JavaScript.

The concept involves having a layout with 100% height where columns extend to the right of the screen, similar to this example : . What I am seeking to achieve is inserting an additional column after the first one, before the second one, and populate it with content such as images or extra links.

I understand how to add content using JavaScript with innerHtml and have also discovered methods to count the number of columns (Get number of columns created by css column-width or How to get css3 multi-column count in Javascript). However, I am unclear on how to obtain the class or ID of a specific column or column break in order to append HTML content accurately.

Is it feasible to instruct the browser through code to "add another column after column #1" or "insert content of 100% height after column #1" or even "create an empty space of XXpx after column #1 (and display an absolutely-positioned div)"?

An illustrative example can be viewed here:

For reference, here's a quick fiddle demonstrating basic HTML/CSS columns: https://jsfiddle.net/p8ar0zpr/1/

<div class="example">
  <h1>Sed dignissim lacinia nunc</h1>
  <p class="lead">Aenean quam. In scelerisque sem at dolor. Sed convallis tristique sem.</p>
  <p>Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. </p>
  <p>Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.  </p>
</div>



 .example {
  -webkit-columns: 320px;
  -moz-columns: 320px;
  columns: 320px;
  -webkit-column-gap: 2em;
  -moz-column-gap: 2em;
  column-gap: 2em;
  height:95%;
  padding:1em;
}
html{height:100%;}
body {
  font-size: 12px;
  font-family: 'Georgia', serif;
  font-weight: 400;
  line-height: 1.45;
  color: #333;
  background: #ecf0f1;
  padding: 0;
  margin:0;
  height:100%;
}

h1 {
  font-size: 2em;
  margin-bottom: 0.5em;
  line-height: 1.2;
}

p {
  margin-bottom: 1.3em;
  text-align: justify;
}

.lead {
  font-variant: small-caps;
  font-size: 1.3em;
  text-align: left;
  font-style: italic;
}

Thank you for your assistance!

Answer №1

One strategy to consider involves evaluating the position of the top-left corner of each p element. The p element at the beginning of each column will have a higher location on the page compared to the one before it (or there might not be any before it).

Here is a sample code snippet that demonstrates this concept by highlighting the p element at the top of each column:

window.addEventListener('load', onDocLoaded, false);
HTMLCollection.prototype.forEach = Array.prototype.forEach;

function onDocLoaded(evt)
{
getColumnTops();
}


function getColumnTops()
{
var paras = document.getElementsByTagName('p');

paras.forEach(checkPosition);
}

var lastValue = 1000000;  
function checkPosition(elem, index, array)
{
if (elem.offsetTop < lastValue)
{
elem.classList.add('colTop');
}
lastValue = elem.offsetTop;
}
.example {
  -webkit-columns: 320px;
  -moz-columns: 320px;
  columns: 320px;
  -webkit-column-gap: 2em;
  -moz-column-gap: 2em;
  column-gap: 2em;
  height:95%;
  padding:1em;
}
html{height:100%;}
body {
  font-size: 12x;
  font-family: 'Verdana', sans-serif;
  font-weight: 400;
  line-height: 1.5;
  color: #333;
  background: #f9f9f9;
  padding: 0;
  margin:0;
  height:100%;
}

h1 {
  font-size: 2em;
  margin-bottom: 0.5em;
  line-height: 1.2;
}

p {
  margin-bottom: 1.3em;
  text-align: justify;
}

.lead {
  font-variant: small-caps;
  font-size: 1.3em;
  text-align: left;
  font-style: italic;
}

.colTop
{
background: rgba(200,0,0,0.25);
}
<div class="example">
  <h1>Lorem ipsum dolor sit amet</h1>
  <p class="lead">1 Aenean quam. In scelerisque sem at dolor. Sed convallis tristique sem.</p>
  <p>2 Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. </p>
  ...
  <p>40 Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus.  </p>
</div> 

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 Angular 2 to execute an interface while making an HTTP GET request

I've managed to successfully retrieve and display data from a JSON object using *ngFor in Angular. However, I am struggling with applying an interface to the retrieved data. This is the content of my interface file: import {Offer} from './offer ...

What is the best way to organize products based on the proximity of users using MongoDB's Geospatial Queries

I'm currently working on a web application that connects users with neighbors to buy and sell products. The app is built using node.js, JavaScript, mongodb, and mongoose. My main issue lies in sorting the products. I want to display products from nea ...

Issue with React-Toastify not displaying on the screen

After updating from React-Toastify version 7.0.3 to 9.0.3, I encountered an issue where notifications are not rendering at all. Here are the steps I followed: yarn add [email protected] Modified Notification file import React from "react" ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Tips for streamlining the filter function using replace and split:

Currently, I am utilizing a filter function alongside replace() and split(). Here is the code snippet: jQuery('table .abc').filter((i, el) => jQuery(el).text(jQuery(el).text().replace('a', 'b').split(' ')[0] + &ap ...

JavaScript events for scrolling horizontally and vertically across multiple browsers

Is there a way to capture mousewheel and touchpad events, including on Mac, using JavaScript? Ideally, I want to get deltaX and deltaY values for both horizontal and vertical movements. I came across a website - - that appears to handle touchpad events ho ...

Having trouble retrieving information from a nested JSON array within a JSON object using JavaScript

I am facing a challenge with extracting specific information from a JSON object that contains an array nested inside. Even though I have experience working with JSON arrays, this particular object is proving to be tricky. For example, when attempting to r ...

"Incorporating images into a dropdown menu by utilizing the option value attribute

After attempting various solutions without success, I am reaching out for help as I am unable to find a fitting solution for my problem. The issue at hand is adding images to select list options based on the option value, with the limitation of not being a ...

Finding and comparing a specific portion of a text in JavaScript: A guide

Can you help me with a JavaScript algorithm that can find a substring within a string? subStringFinder('abbcdabbbbbck', 'ab') This should return index 0. Similarly, subStringFinder('abbcdabbbbbck', 'bck') should ...

Sending the form without triggering a new window or tab

My goal is to submit a form using Ajax so that it doesn't open a new tab every time I submit it, which can be quite annoying especially when creating multiple images. The current method of submitting the form works fine, but it opens a new tab each t ...

Issue with Knockout.js: Parsing error in bindings - SyntaxError: Unexpected token `};`

Take a look at this example. I've tried to simplify it as much as possible, but I'm still struggling to figure out where I went wrong. Any help would be greatly appreciated )) P.S Stack Overflow requires code, not just a link to jsfiddle. H ...

Having trouble locating my images in a project created with Webpack-simple and Vuejs using vue-cli

My folder structure looks like this: https://i.sstatic.net/dEhAN.png Since my website is simple, I prefer using just a json file to feed data instead of requiring an administrator. In my Cases.vue file, I have a v-for loop that iterates through my data/ ...

Is there a way to distinguish between a request from prerender.io (crawlers) and a real user (browser) using JavaScript?

I needed to identify whether requests were coming from prerender.io (a library used for rendering AngularJS applications for web crawlers) or from real users. If the request was from prerender, I had to redirect to a page specifically designed for SEO purp ...

React returns Not a Number when summing up numbers

On the cart page, I am calculating the total for each product. Each object contains quantity and price which are multiplied to get the total value of the product. However, since users can have multiple products in their cart, I need to sum the totals of ...

What is the best way to navigate from one div to a particular slide within a slider?

Let's say I have two web pages: index.html and page.html. On page.html, there is a slider with 9 slides created using the plugin StackSlider. Now, when a link on index.html is clicked, I want to navigate to a specific slide, like slide number 4, on pa ...

Utilize JavaScript to activate a new browser tab and monitor its status for closure

When I attempt to open a new tab using JavaScript and track when it is closed, none of the events are being triggered. All the examples I found reference the onbeforeunload event for the current window, not for other window objects. window.addEventListe ...

the primary way JavaScript defines its "this" binding

As I delve into a book, it mentions that this within a function can be established in four different ways: default, implicit, explicit binding, and through the use of the new syntax. Regardless of the method, this is determined at the time of the function ...

Delete the "img" and "a" elements from the content within the specified node

Is it possible to only extract text from my HTML content? var sb = new StringBuilder(); doc.LoadHtml(inputHTml); foreach (var node in Doc.DocumentNode.ChildNodes) { if (node.Name == "strong" || node.Name == "#text" || node.Name == "br" || no ...

Angular - Execute a function once the observable has finished

I am currently working with a 2 part process that involves importing a list of usernames in Component 1, submitting it to a service, and then using the returned user profile data in Component 2. The issue I am facing is that when I receive the data back f ...

"Sharing JSON data with the client side using Express and Node.js: A step-by-step guide

I am currently working on an application that requires sending form data through XMLHttpRequest. The process involves validating the form data on the server side and then providing feedback to the client based on the validation result. In this project, I a ...