What is the method for creating an element on the right side of a heading using jQuery/JavaScript?

I am seeking assistance with a project of mine. To illustrate, I have provided a brief code snippet below.

Let's consider a scenario where we have two sections denoted by the class "box". Inside each box, there are elements containing a heading and specific content. For the purposes of this example, let's focus on the headings.

My objective is to insert elements into the right box that align directly behind the text of the headings. It's crucial to mention that these elements should not be pseudo-elements as certain functions in my project are incompatible with them.

How can I accurately position an element behind the text of another element?

generateNewItems();

function generateNewItems() {
  let elements = $(".box#test div");
  
  for (let elem of elements) {
    let heading = $(elem).children("h3");
    
    let leftPos = 10; /* HOW? */
    
    let el = $("<div>").addClass("new-item").css({
        "left": leftPos,
      "top": -3
    });
    
    $(elem).append(el);
  }
}
.new-item {
  position:absolute;
  background:red;
  height:30px;
  width:30px;
}

.box {
  width:50%;
  background:lightblue;
  float:left;
}

.box > div {
  position:relative;
}

.box > div > h3 {
  background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
  <div>
    <h3>test-one</h3>
  </div>
  <div>
      <h3>test-two</h3>
  </div>
</div>
<div class="box" id="test">
  <div>
    <h3>small-text</h3>
  </div>
  <div>
      <h3>long-sample-text</h3>
  </div>
</div>

Answer №1

Here is a solution:

To achieve this effect, add a <span> tag within the <h3> element. Set the height to 100% and the width to 30px with a CSS rule of position: relative.

Within that span, insert another span element with position:absolute and customize its size and color according to your preferences.

Important note: This technique will work regardless of whether the text alignment is left, center, or right, but only when the content inside the <h1> does not take up the full width of the containing <div>

generateNewItems();

function generateNewItems() {
  let elements = $(".box#test div");
  
  for (let elem of elements) {
    let heading = $(elem).children("h3");
    
    let el1 = $("<span>").addClass("new-item-fake");
    let el2 = $("<span>").addClass("new-item");
    $(el1).append(el2);
    $(heading).append(el1);

    
  }
}
.new-item-fake {
display: inline-block;
position: relative;
  height:100%;
  width:30px;

}
.new-item {
  position: absolute;
  display: block;
top: -21px;
left: 0px;
  height:30px;
  width:30px;


background: red;
}

.box {
  width:50%;
  background:lightblue;
  float:left;
}

.box > div {
  position:relative;
}

.box > div > h3 {
text-align: right;
  background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
  <div>
    <h3>test-one</h3>
  </div>
  <div>
      <h3>test-two</h3>
  </div>
</div>
<div class="box" id="test">
  <div>
    <h3>small-text</h3>
  </div>
  <div>
      <h3>long-sample-text</h3>
  </div>
</div>

Answer №2

If you are considering altering your HTML structure, one option could be to wrap your texts in span elements and then utilize getBoundingClientRect to determine their size.

To locate those elements, you can use the following code:

let heading = $(elem).find(""h3 > span");

Next, you can adjust the left style of the rectangles with:

let leftPos = heading[0].getBoundingClientRect().width;

(Use heading[0] since getBoundingClientRect is a Javascript function, not jQuery)

generateNewItems();

function generateNewItems() {
  let elements = $(".box#test div");
  
  for (let elem of elements) {
    let heading = $(elem).find("h3 > span");
    
    let leftPos = heading[0].getBoundingClientRect().width;
    
    let el = $("<div>").addClass("new-item").css({
        "left": leftPos,
      "top": -3
    });
    
    $(elem).append(el);
  }
}
.new-item {
  position:absolute;
  background:red;
  height:30px;
  width:30px;
}

.box {
  width:50%;
  background:lightblue;
  float:left;
}

.box > div {
  position:relative;
}

.box > div > h3 {
  background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
  <div>
  <h3><span>test-one</span></h3>
  </div>
  <div>
  <h3><span>test-two</span></h3>
  </div>
</div>
<div class="box" id="test">
  <div>
   <h3><span>small-text</span></h3>
  </div>
  <div>
  <h3><span>long-sample-text</span></h3>
  </div>
</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

refreshing a javascript function without the need for reloading

Attempting to create an embedded web server using the Nano WiReach SMT. Here is the code that has been written so far: <HTML> <HEAD> <SCRIPT LANGUAGE=JavaScript> function swapImage() { var val1 ...

Is it possible for a navbar in CSS to collapse based on its width?

At the moment, I am utilizing Bootstrap v3.3.6 and jQuery v1.9.1. My current project involves a horizontal navbar that collapses once it reaches a specific screen resolution. I am pleased with how this feature operates and wish to maintain the same breakpo ...

Toggle camera on and off using a single button in Javascript

I'm encountering an issue with my camera functionality. I've implemented a button to open the camera (see code below), but I'm unsure how to turn off the camera when the same button is clicked. Snippet of my code: Button: <a type=" ...

What is the best way to remove an instance of the MagicSuggest JQ plugin?

Recently, I've been utilizing MagicSuggest in my forms and have encountered situations where I need to dismantle it and reinstate the input field. I have carefully reviewed the entirety of the documentation but am unable to locate a method to achieve ...

Unexpected behavior encountered when using TypeScript type declarations

I am currently working on a Gatsby side project incorporating Typescript for the first time. I initially expected Typescript to behave similarly to PHP type declarations, but I have encountered some unforeseen issues. Despite feeling confident in my Typesc ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Separate a tab delimited text file and store it into an array using JavaScript

Looking to parse a text file with tab-separated values in JavaScript and add them to an array? Here's how you can achieve this while excluding the header: Id Symbol 1 A 2 B 3 C 4 D 5 E 6 F 7 G This is what I have attempted so far: va ...

Looping through an array of nested objects using Vue

I have encountered a challenge with accessing specific data within an array that I am iterating over. The array is structured as follows, using Vue.js: companies: [ name: "company1" id: 1 type: "finance" additionalData: "{& ...

Using jQuery to dynamically update the CSS of one table column depending on the attribute of another column

Welcome to my HTML table <!DOCTYPE html> <html> <body> <table> <thead> <th>Title1</th> <th>Title2</th> </thead> <tbody> <tr> <td><input type="checkbox" id=0 /></td> ...

Hyperlinking Github.io Images

I'm facing an issue regarding image paths on github.io. It seems like the images from my github repository are not displaying properly (I made sure to check spelling and case sensitivity). I'm running out of ideas, so maybe you can help me spot m ...

What are some ways to make use of data fetched through ajax requests?

This code is functioning properly and successfully retrieving data from the server. The data consists of [{id: someId, name: someName}, {..}....{...}] SJA.ajax(dataToSend, function (respond) { if (respond) { for (var i in respond) { console ...

How to remove the scrollbar from the main div in a Bootstrap layout

Currently, I am in the process of creating a registration page using HTML, CSS, and Bootstrap5. I have a couple of questions: Within my code, there is a fixed height for the footer set at 55px. I am uncertain if this is considered good practice because ...

Utilizing WebView and Javascript for Push Notifications

Is it feasible to utilize javascript on an external page within a WebView application to trigger push notifications? (For instance, if I have a function located at example.com/news, would it be possible to send a push notification from there?) Appreciate ...

What is the most effective way to extract content values from different divs for calculation using jQuery?

I am working on creating a function that retrieves the content values from the <div class="rowtabela"> div and reads the nodes of <div class="item v_...">. Check out my code below: <div class="adicionados" id=& ...

Prevent users from entering past dates in the date input field

In my project, I have decided to use input type date instead of datepicker. Is there a way to prevent users from selecting back dates in input type date without using datepicker? If you have any suggestions, please let me know. Thank you! ...

The angular-block-ui feature fails to run my HTML code as a personalized message

I'm looking to enhance my UI by implementing a blocking feature with a spinner display. My attempt involved the following code: blockUI.start("<div class='dots-loader'>Minions are Working!</div>"); // code for fetching data ...

The ES6 class Inheritance chain does not properly utilize the instanceof keyword

My curiosity lies in understanding why the instanceof operator fails to work properly for the inheritance chain when there are multiple chains of inheritance involved. (optional read) How does the instanceof operator function? When using obj inst ...

Exploring the best practices for organizing logic within Node.js Express routes

I'm currently utilizing the https://github.com/diegohaz/rest/ boilerplate, but I am unsure about the best practice for implementing logic such as QR code generation and additional validation. My initial thought was to include validation and password ...

I'm encountering an error with the *ngIf directive in my Angular reactive form - any ideas on

Despite my reputation, I have a question that is causing me some confusion. I am trying to create a reactive form using an example on Stackblitz. While everything seems fine in Stackblitz and the code works correctly there, I encounter an error in VS Code ...

Anticipated request for spy navigation with path '/members' was expected, but unfortunately was not triggered

I am facing an issue with a service method that performs an HTTP delete operation. The expected behavior is that upon successful deletion, the page should be redirected to another location. However, during testing, I noticed that the router navigation func ...