Dealing with alternating rows in a dynamic manner: tips and tricks

Exploring an example scenario: (view live demonstration)

Sample HTML structure:

<div class="wrapper">
    <div city_id="1" class="odd">Street Name #1 in city 1</div>
    <div city_id="3" class="even">Street Name #2 in city 3</div>
    <div city_id="2" class="odd">Street Name #3 in city 2</div>
    <div city_id="1" class="even">Street Name #4 in city 1</div>
    <div city_id="1" class="odd">Street Name #5 in city 1</div>
    <div city_id="3" class="even">Street Name #6 in city 3</div>
    <div city_id="2" class="odd">Street Name #7 in city 2</div>
    <div city_id="3" class="even">Street Name #8 in city 3</div>
    <div city_id="1" class="odd">Street Name #9 in city 1</div>
</div>
<select>
    <option value="">Please select...</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

Select CSS styles:

.odd {
    background-color: #777;
}
.even {
    background-color: #aaa;
}

Utilized JavaScript:

$(function() {
    $("select").change(function() {
        var city_id = $("option:selected", this).val();
        $("div[city_id]").each(function() {
            $(this).toggle($(this).attr("city_id") == city_id);
        });
    });
});

The goal is to retain alternating colors even when certain rows are hidden.

Seeking a solution through solely CSS or, if not feasible, considering JavaScript/jQuery methods.

Answer №1

Check out this neat idea! Adjust the row's class dynamically as you switch the selected index.

http://jsfiddle.net/4Bjbc/5/

$(function() {
    $("select").change(function() {
        var city_id = $("option:selected", this).val();
        $("div[city_id]").each(function() {

            $(this).toggle($(this).attr("city_id") == city_id);

        }).filter(":visible")  ///filter the visible ones

          .attr("class",function(index,$class){                

            ///if you don't want to miss out the other classes
            return index%2 == 0 ? $class.replace("odd","even") : $class.replace("even","odd"); 
        });
    });
});

Answer №2

Utilize JavaScript to dynamically assign the classes 'odd' or 'even' by iterating through the items. If the items are visible, switch the class accordingly to create alternating styles.

Answer №3

To apply styles using CSS, you can do the following:

.container div:nth-child(even) { background-color: #777; }
.container div:nth-child(odd) { background-color: #aaa; }

It's important to note that the above code will not consider hidden rows. To address this, you can refine the selector like this:

.container div.visible:nth-child(even) { background-color: #777; }
.container div.visible:nth-child(odd) { background-color: #aaa; }

Make sure that all visible elements have the visible class for the styles to apply correctly.

Answer №4

To implement this functionality with jQuery, you can utilize the change event and the following code:

$('.wrapper div:visible:even').css({
    'background-color': '#777'
});
$('.wrapper div:visible:odd').css({
    'background-color': '#aaa'
});

COMPLETE CODE

$("select").change(function() {
    var city_id = $("option:selected", this).val();
    $("div[city_id]").each(function() {
        $(this).toggle($(this).attr("city_id") == city_id);
    });
    $('.wrapper div:visible:even').css({
        'background-color': '#777'
    });
    $('.wrapper div:visible:odd').css({
        'background-color': '#aaa'
    });
});

This method ensures that the background color is applied only to visible rows.

Check out the demo on this fiddle link: http://jsfiddle.net/4Bjbc/3/

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

The child element fails to increase in size if the parent element has a minimum height specified

I'm having trouble getting min-height to work properly. The issue is that my child element doesn't inherit the height of its parent, so it's not setting its own height correctly. How can I resolve this? #middle_Wrapper { width: 100%; mi ...

The output from the Node.js child_process.exec command returned null for stdout, yet stderr was not empty

I'm currently working with a simple code that runs java -version in the command line to check if Java is installed on the user's system. Interestingly, when I execute this code, the stdout does not display anything, but the stderr shows the expe ...

Issue with reactivity in deeply nested objects not functioning as expected

Currently, I am utilizing Konvajs for my project. In simple terms, Konvajs provides a canvas for drawing and editing elements such as text nodes that can be manipulated by dragging and dropping. These nodes are organized within groups, which are then added ...

Conceal the Ajax Div and display the Loader Div while waiting for the data to be

Trying to show a loader div until the Ajax-populated div is returned. Want to hide "responseDiv" until it's filled with Ajax data and display a loading div in the meantime. #loading { background: url('images/loading.gif') no-repeat cent ...

Error: Attempting to access the 'HotelInfo' property of an undefined variable led to an uncaught TypeError

//initiating an AJAX request to access the API jQuery(document).ready(function() { jQuery.ajax({ url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&a ...

Having difficulty specifying numerical entries only

I have been attempting to create an input field that only accepts numbers, but for some reason it still allows letters to be entered. Why is this happening? <input type="number" pattern="[0-9]" ...

How to send a JavaScript object to a Django view using jQuery and AJAX

How can I use jQuery to send a JavaScript object to a Django server? $.ajax({ type: 'POST', url: '/fetch-items/', data: {'foo': 'bar', 'foobar': {'spam': 'eggs'} }, success: functio ...

Issue encountered during creation of a polyline in Cesium

When attempting to create a polyline in my ReactJs app using the code below, I encountered an error message stating "DeveloperError: Expected value to be greater than or equal to 0.0125, the actual value was 0." Can someone shed some light on why this er ...

What is the best way to execute a Java script using AJAX from a different file?

I have included multiple ajax scripts in the main body of the Django template. However, when I try to run them from a separate JS file, they do not seem to work. This is an example of one of the working scripts within the body template: <!--Add product ...

Issue with spacing in 3x3 photo rollover grid

I am currently working on a 3x3 grid layout featuring image roll overs. Within this layout, the three images on the second row are linked to pages on the website. My goal is to incorporate a 4px padding around all columns and rows, centered at 1024x600 on ...

Error message for Joi when validating a nested array of objects

I have received user input from the client side and am performing backend validation using Joi. const Joi = require("joi") const schema = Joi.array().items( Joi.object().required().keys({ name: 'filter_list', value: Joi.array(). ...

Why is the editor not displaying the correct line number when the enter key is pressed repeatedly in JavaScript?

I am currently working on developing an editor using JavaScript. My goal is to display a line count (e.g., 1, 2, 3) whenever the user presses 'Enter' to change lines. I have successfully managed to count the line changes upon pressing 'Enter ...

A step-by-step guide to displaying an image preview when hovering over a cell in a

How can I display an image when hovering over a <td> in a datatable after clicking a button to fill the table with data? Here is my code: <script> if($.fn.dataTable.isDataTable( '#example' )){ var table = $('#example'). ...

The React modal refuses to disappear, stubbornly clinging to the original component it sprang from

Hey there, I'm a beginner in learning React and I'm encountering an issue with my popup modal component. Even after showing the modal, I can still interact with and click on the main UI elements. Can anyone assist me with this problem? https://i ...

Tips for interacting with the DOM in an Angular 4 application

I am trying to call the addItems method, but I keep getting an error: Uncaught TypeError: this.addItems is not a function Currently, I am using Angular 4 along with jQuery and the fullpage.js library. page-content.component.ts import { Component, OnI ...

Troubleshooting React's failure to start with node.js running behind an Nginx Reverse Proxy

This is my first attempt at setting up a Node.js server in production (other than one Meteor server), and I've run into a problem that I can't figure out on my own. I have built an application using React. Here is the server code: // Imports va ...

Employing jQuery to save the href value as a fresh variable

There is an anchor tag with id 'item-1' that needs to be stored in a new variable called 'href'. The tag looks like this: <a id='item-1' href='#something'> To achieve this using jQuery, what approach should be ...

Finding the label that is linked to the current DIV or textarea by its "for" property

I am working on a project that involves two elements - a textarea and a div. Each element has a label attached to it using the "for" attribute in HTML. <textarea id="txta_1" class="txta" cols="40" rows="3" onkeyup ...

Discovering the art of interpreting the triumphant outcome of an Ajax request with jquery/javascript

I recently encountered a challenge with my function that deals with a short JSON string: <script id="local" type="text/javascript"> $( document ).ready(function() { $('tr').on('blur', 'td[contenteditable]', functi ...

AngularJS fails to trigger window scroll event

Although I have come across similar inquiries regarding this issue, none of the solutions have proven to be effective for me. Currently, I am working with AngularJS and I am attempting to detect the scroll event. Despite trying numerous variations to capt ...