Tips for altering the color of spans that share a common top position without affecting the surrounding sibling elements above or below

Is there a way to change the color of spans with the same top position, excluding sibling elements above or below, in a paragraph made up of spans?

I've been working on how to change the color of the line of span tags that contain another span with the "active" class appended.

Any suggestions on achieving this?

var next = $(".active").next();
var prev = $(".active").prev();

var activeWord = $(".active");
while ((next.position().top && prev.position().top) === activeWord.position().top) {
  next.css({
    color: "red"
  });
  prev.css({
    color: "red"
  });
}
.word {
  font-family: arial, sans-serif;
  font-size: 14px;
  line-height: 1.25em;
}
.active {
  color: red;
}
.active-row {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div class="content">
  <span class="word">Lorem</span>  <span class="word">ipsum</span>  <span class="word">dolor</span>  <span class="word">sit amet</span>  <span class="word">consectetur</span>  <span class="word">adipiscing</span>  <span class="word">elit</span>  <span class="word">sed</span> 
  <span
  class="word">do</span> <span class="word">eiusmod</span>  <span class="word">tempor</span>  <span class="word">incididunt</span>  <span class="word">ut</span>  <span class="word">labore</span>  <span class="word">et</span>  <span class="word">dolore</span>  <span class="word">magna</span> 
    <span
    class="word">aliqua</span> <span class="word">Ut</span>  <span class="word">enim</span>  <span class="word">ad</span>  <span class="word">minim</span>  <span class="word">veniam</span>  <span class="word">quis</span>  <span class="word">nostrud</span>  <span class="word">exercitation</span> 
      <span
      class="word">ullamco</span> <span class="word">laboris</span>  <span class="word">nisi</span>  <span class="word">ut</span>  <span class="active word">aliquip</span>
        <span class="word">ex</span>  <span class="word">ea</span>  <span class="word">commodo</span>  <span class="word">consequat</span>  <span class="word">Duis</span>  <span class="word">aute</span>  <span class="word">irure</span>  <span class="word">dolor</span> 
        <span
        class="word">in</span> <span class="word">reprehenderit</span>  <span class="word">in</span>  <span class="word">voluptate</span>  <span class="word">velit</span>  <span class="word">esse</span>  <span class="word">cillum</span>  <span class="word">dolore</span>  <span class="word">eu</span> 
          <span
          class="word">fugiat</span> <span class="word">nulla</span>  <span class="word">pariatur</span>  <span class="word">Excepteur</span>  <span class="word">sint</span>  <span class="word">occaecat</span>  <span class="word">cupidatat</span>  <span class="word">non</span> 
            <span
            class="word">proident</span> <span class="word">sunt</span>  <span class="word">in</span>  <span class="word">culpa</span>  <span class="word">qui</span>  <span class="word">officia</span>  <span class="word">deserunt</span>  <span class="word">mollit</span>  <span class="word">anim</span> 
              <span
              class="word">id</span> <span class="word">est</span>  <span class="word">laborum</span>
</div>

Answer №1

First and foremost, it is crucial not to simultaneously check the previous and next element (your code did not do this correctly as

(next.position().top && prev.position().top)
would just result in a boolean value) - since an element could have one sibling on the same line while the other might be on the previous or next line.

Additionally, you neglected to advance both the next and previous elements for the subsequent iterations.

var next = $(".active").next();
var prev = $(".active").prev();

var activeWordPositionTop = $(".active").position().top;

while (next.position().top === activeWordPositionTop) {
  next.css({
    color: "red"
  });
  next = next.next(); 
}
while (prev.position().top === activeWordPositionTop) {
  prev.css({
    color: "red"
  });
  prev = prev.prev();  
}
.word {
  font-family: arial, sans-serif;
  font-size: 14px;
  line-height: 1.25em;
}
.active {
  color: red;
}
.active-row {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div class="content">
  <span class="word">Lorem</span> <span class="word">Lorem</span> <span class="word">Lorem</span>  <span class="word">ipsum</span>  <span class="word">dolor</span>  <span class="word">sit amet</span>  <span class="word">consectetur</span>  <span class="word">adipiscing</span>  <span class="word">elit</span>  <span class="word">sed</span> 
  <span class="word">do</span> <span class="word">eiusmod</span>  <span class="word">tempor</span>  ....
    <span class="word">laborum</span>
</div>

(I inserted two additional Lorem words at the beginning to demonstrate that the active word aliquip was coincidentally the first word on its line within the standard width of the code snippet box - positioning it slightly more towards the center makes it clearer that the code functions correctly.)

Answer №2

Simply update the prev and next variables within the while loop

var next = $(".active").next();
var prev = $(".active").prev();

var activeWord = $(".active");

while (next.position().top === activeWord.position().top  || prev.position().top === activeWord.position().top) {
  next.css({
    color: "red"
  });
  prev.css({
    color: "red"
  });
//simply update prev & next variables
prev = next;
next = next.next();
}
.word {
  font-family: arial, sans-serif;
  font-size: 14px;
  line-height: 1.25em;
}
.active {
  color: red;
}
.active-row {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div class="content">
  <span class="word">Lorem</span>  <span class="word">ipsum</span>  <span class="word">dolor</span>  <span class="word">sit amet</span>  <span class="word">consectetur</span>  <span class="word">adipiscing</span>  <span class="word">elit</span>  <span class="word">sed</span> 
  <span
  class="word">do</span> <span class="word">eiusmod</span>  <span class="word">tempor</span>  <span class="word">incididunt</span>  <span class="word">ut</span>  <span class="word">labore</span>  <span class="word">et</span>  <span class="word">dolore</span>  <span class="word">magna</span> 
    <span
    class="word">aliqua</span> <span class="word">Ut</span>  <span class="word">enim</span>  <span class="word">ad</span>  <span class="word">minim</span>  <span class="word">veniam</span>  <span class="word">quis</span>  <span class="word">nostrud</span>  <span class="word">exercitation</span> 
      <span
      class="word">ullamco</span> <span class="word">laboris</span>  <span class="word">nisi</span>  <span class="word">ut</span>  <span class="active word">aliquip</span>
        <span class="word">ex</span>  <span class="word">ea</span>  <span class="word">commodo</span>  <span class="word">consequat</span>  <span class="word">Duis</span>  <span class="word">aute</span>  <span class="word">irure</span>  <span class="word">dolor</span> 
        <span
        class="word">in</span> <span class="word">reprehenderit</span>  <span class="word">in</span>  <span class="word">voluptate</span>  <span class="word">velit</span>  <span class="word">esse</span>  <span class="word">cillum</span>  <span class="word">dolore</span>  <span class="word">eu</span> 
          <span
          class="word">fugiat</span> <span class="word">nulla</span>  <span class="word">pariatur</span>  <span class="word">Excepteur</span>  <span class="word">sint</span>  <span class="word">occaecat</span>  <span class="word">cupidatat</span>  <span class="word">non</span> 
            <span
            class="word">proident</span> <span class="word">sunt</span>  <span class="word">in</span>  <span class="word">culpa</span>  <span class="word">qui</span>  <span class="word">officia</span>  <span class="word">deserunt</span>  <span class="word">mollit</span>  <span class="word">anim</span> 
              <span
              class="word">id</span> <span class="word">est</span>  <span class="word">laborum</span>
</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

Is there a simple way to create a clickable popup menu without using JavaScript?

/*---Creating a Popup Menu with CSS---*/ .box{ position:fixed; top: 0.1%; left: 14px; display: inline-block; cursor: pointer; } ul{ list-style-type: none; } ul li{ font-family: Lato; padding: 10px; } ul li a{ text-decoration: none; color: black; } ul li:ho ...

What is the best way to access an Ajax response outside of its function using JQuery?

Just starting out with JQuery and wondering how to utilize the Ajax response ( HTTP GET ) outside of the function in my code snippet below: $.ajax ({ type: "GET", url: "/api", success: success, error: error ...

Seeking a solution for resolving the problem with HTML1402 when using jquery URL in Internet Explorer?

Why is it that only IE (and not any other browser) gives me the error HTML1402: Character reference is missing an ending semi-colon “;” with this code: <!DOCTYPE HTML> <html> <head> <script src="http://code ...

"Storing a collection of PDF files in an array in TypeScript Angular - A step-by-step

Here we have an HTML code snippet that includes an input file element with Angular: <input type="file" class="btn btn-info" id="archivoPDF" #PDFfile value="Seleccionar PDF(s)" accept="application/pdf" multiple /> And this is the TypeScript code sni ...

Enter your password using the text input field on Internet Explorer 8

I'm currently developing a website and facing an issue with the password input field: When clicking on it in browsers like IE9, Chrome, and Mozilla, the text changes to allow entry of the password. However, in IE8, clicking on the input field leaves ...

Animating toasts in Bootstrap

Exploring the options available at https://getbootstrap.com/docs/4.3/components/toasts/ To customize your toasts, you can pass options via data attributes or JavaScript. Simply append the option name to data- when using data attributes. If you're lo ...

working with html data in a bootstrap modal using javascript

Utilizing an id, I pass data to a bootstrap modal and link that id with stored data. $("#fruit").html($(this).data("fruit")); In addition, I am appending data to the bootstrap modal $('#mymodal').find('.modal-body').append('< ...

The Limits of JavaScript Tables

Currently facing an issue with a webpage under development. To provide some context, here is the basic layout of the problematic section: The page features a form where users can select from four checkboxes and a dropdown menu. Once at least one checkbox ...

How can I insert an HTML/PHP code snippet into a <ul> list using JavaScript?

My upload.php file saves images into an uploads/ folder within my main directory. I am looking to dynamically add a new li tag to my index file each time an image successfully uploads. Here is a snippet from index.php: <ul> <li><im ...

What is the reason for the website allowing me to scroll towards the right?

I'm encountering a strange issue with my code that I can't seem to figure out. The website keeps letting me scroll to the right as if there's an image or something off-screen, even though there isn't anything there. Any idea why this is ...

The challenge of harmonizing variables in PHP and JavaScript

I have a PHP script that generates an HTML table displaying data from a MySQL database. <?php include 'connexion.php'; session_start(); $idfirm = $_REQUEST['idfirm']; $namefirm = $_REQUEST['namefirm']; The table rows are ...

Wrapping a group of elements with opening and closing tags using jQuery

I have a collection of distinct elements, like so: <section class="box-1"></section> <section class="box-2"></section> <section class="box-3"></section> My objective is to enclose all three elements within a div with a ...

Having difficulty showing the successful JSON output in either the view or an alert

In my CodeIgniter project, I have three input fields named name, emp_id, and crm_id. I enter the id value and send it to the controller via AJAX and JSON to retrieve all information related to that id. The issue is that while I can see the correct output i ...

"Exploring the Power of Angular with HTML Checkboxes

I am trying to display a checkbox as either checked or unchecked based on the value of a variable {{CurrentItem.STATUS}}, which can be either 1 or 0. Is there an Angular solution that does not require any javascript/typescript to achieve this? I want the ...

CSS problem: alignment issue between text and checkbox

I'm experiencing a CSS style issue where the text box and text are not aligned properly. Can someone assist me in fixing this problem? Below is the code I am using: Thank you for your help. <div> <input type="checkbox" ...

Using Javascript to test a specific item in an asp Listbox

Let's consider a scenario where there is ListBox1 containing the following listitem: <asp:ListItem Value="No.1">No.1</asp:listitem> In addition, we have a label for a test purpose: <asp:Label ID="lblLabel" runat="server" Text="Label ...

Compatibility Issue between Jquery UI CheckBox Button and Click Function in IE8

Situation: After calling addButton() function in jQuery, the checkbox element is successfully turning into a button. However, the click event that should trigger an alert message is not functioning. This issue seems to be specific to IE-8 compatibility. ...

I want to know how to move data (variables) between different HTML pages. I am currently implementing this using HTML and the Django framework

I am currently working on a code where I am fetching elements from a database and displaying them using a loop. When the user clicks on the buy button, I need to pass the specific product ID to another page. How can I retrieve the product ID and successful ...

The makeStyles feature is currently not functioning properly in the latest version of Next.js with Material UI v5

Currently, I am utilizing nextjs along with material ui in my project "@mui/material": "^5.0.1", "@mui/styles": "^5.0.1", Below is the code snippet of my component structure import { AppBar, Toolbar, Typography, Box ...

Looking for assistance with $.ajax - How can I send an object with key-value pairs?

I want to utilize $.ajax to send data in this manner: $.ajax({'url': 'my.php', 'type': 'POST', 'data': arr, 'success': function(response) { alert(res ...