`How can the background color be altered based on specific conditions?`

I am attempting to modify the background color. My goal is to change every odd result to a light green (#f0f5f5) to avoid a large white space when the result ends in an even number. I would also like to change the background color of the pagination section to light green when the result ends in an even number. The search results only display 5 results, so it could be the 2nd and 4th ones.

search.addWidgets([
  instantsearch.widgets.searchBox({
    container: '#searchbox',
  }),
  instantsearch.widgets.hits({
    container: '#Algolia_Result',
    transformItems: function (items) {
      return items.map(function (item) {
        if (item.objectType === 'Startup') {
          item._isDescription = isNotNull(item.description);
  
        } else if (item.objectType === 'NEWS') {
          item._isSource = isNotNull(item.source);

        } else if (item.objectType === 'Comment') {
            
          item._isComment = isNotNull(item.comment);
         
     
        return item;
      });
    },
     templates: {
      empty: '<div id="empty">No results have been found for {{ query }}.</div><br>',
      item: `
        <a href="{{linkUrl}}" target="_blank">
        <div class="algolia_container">
            <div class="item1">
                <div id="images"><img src="{{logoUrl}}" alt="{{hits-image}}" id="hits-image"></div>
                <div id="objTyeps"><span class="objectType {{objectCss}}">{{objectType}}</span></div>
            </div>
            <div class="item2">
                <div id="objectTitle">
                <span id="titleForDisplay">{{#helpers.highlight}}{ "attribute": "titleForDisplay" }{{/helpers.highlight}}</span>
                </div>
            </div>
            <div class="item3">


                {{#_isLocation}}
                    <div id="location">{{#helpers.highlight}}{ "attribute": "location" }{{/helpers.highlight}}</div>
                {{/_isLocation}}
                
            </div>
        </div></a>
      `, 
    },
  }),
  instantsearch.widgets.pagination({
    container: '#pagination',
  }),
]);
#Algolia_Result > div > div > ol > li:nth-child(odd){background-color: #f0f5f5;}

.ais-Pagination-item {
    display:inline;
    padding: 5px;
    margin: 0 5px;
    border: 1px solid #E8E8E8;
    border-radius:5px;
    font-size:18px;
}

.ais-Pagination-list {
    text-align: center;
    height:45px;
    padding-top: 10px;
}

.ais-Pagination-item:hover {
  background-color: #DCDCDC;
  transition: background-color .2s;
}

.ais-Pagination-item--selected{
  background-color: #E8E8E8;
}
<div id="searchbox"></div>      
    <div id="results">
        <div id="Algolia_Result"></div>
        <div id="pagination"></div>
    </div>
                        

This is acceptable

This needs to be addressed, as the background color of the pagination area must match the last result, indicating it must be green

This is the console output that I am seeing.

Answer №1

To change the background color of the pagination row, you can use JavaScript to count the number of results and apply a color if the result count is even.

Take a look at the example provided below.

Example 1 contains an odd number of result rows, and the CSS styling works correctly, as in your working example.

Example 2 has an even number of result rows and applies the pagination background color using JavaScript.

// Count the rows
let numRows = document.querySelectorAll('#example-2 .row').length
// If the number of rows is even
if (numRows % 2 == 0) {
  // Apply the background color to the pagination row
  document.querySelector('#example-2 .pagination').style.backgroundColor = '#eee'
}
.container {
  border: 1px solid #000;
  margin-bottom: 5px;
}

.row:nth-child(odd) {
  background-color: #eee;
}
Example 1
<div id="example-1" class="container">
  <div>
    <div class="row">Row 1</div>
    <div class="row">Row 2</div>
    <div class="row">Row 3</div>
  </div>
  <div>
    <div class="pageination">Pagination Row</div>
  </div>
</div>

Example 2
<div id="example-2" class="container">
  <div>
    <div class="row">Row 1</div>
    <div class="row">Row 2</div>
  <div>
  <div>
    <div class="pagination">Pagination Row</div>
  </div>
</div>

EDIT: In your scenario, you should include the following JavaScript code.

<script>
  let numRows = document.querySelectorAll('.ais-Hits-item').length
  if (numRows % 2 == 0) {
    document.querySelector('.ais-Pagination-list').style.backgroundColor = '#eee'
  }
</script>

EDIT 2: After reviewing your code sandbox, it appears that the issue arises because the JavaScript that calculates the row count is executed before the rows are rendered by Algolia.

To resolve this, we need to place our row counting JavaScript within an Algolia callback function that runs after the rows have been rendered. This can be achieved using the algolia search.on('render', ...) event callback.

Try the following code:

search.on('render', () => {
  let numRows = document.querySelectorAll('.algolia_container').length;
  if (numRows % 2 === 0) {
    document.querySelector('#pagination').style.backgroundColor = 'red';
  } else {
    document.querySelector('#pagination').style.backgroundColor = 'transparent';
  }
});

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

Do you know of any HTML Validators that are compatible with Maven?

Currently, I am working on a project that consists of multiple HTML files. In order to ensure a smooth Maven build process, I am looking for a validator that can perform the following checks: Validate the syntax of the files (such as ensuring all opening ...

The criteria is not fulfilled by either item.area_partition.homepage_show or item.area_partition.name in accordance with my needs

I am having an issue with some code snippet: <Col span="8" v-for="(item,index) in this.data" > <Card> <p slot="title" style="">{{ item.area_partition.homepage_show || item.area_partition. ...

What is the best way to import and export modules in Node.js when the module names and directories are given as strings?

Here is the structure of my folder: modules module-and index.js module-not index.js module-or index.js module-xor index.js moduleBundler.js The file I'm currently working on, moduleBundler.js, is re ...

Exploring Event Listening in HTML5 Programming

Having been an AS3 developer, I'm accustomed to this: addEventListener(Event.RESIZE, onResize); Currently diving into Typescript/JS/HTML5, I've noticed various ways of accomplishing tasks. I particularly prefer this method: window.addEventLis ...

How can I get video playback in IOS to work with Videogular2 using HLS?

I recently integrated videogular2 into my Angular 6 app to display HLS streams. Everything seems to be working smoothly on desktop and Android devices, but I encountered an error when testing on IOS: TypeError: undefined is not an object (evaluating &apos ...

Property '{}' is not defined in type - Angular version 9.1.1

Currently, I am working with Angular CLI version 9.1.1 and I am attempting to update certain data without updating all of it. form: UserInfo = {adresse : {}}; UserInfo.interface export interface UserInfo { id_user: string; username: string; em ...

"Retrieve a specific object from a JSON file using NextJS based on its ID

NextJs is the framework I am currently utilizing for my project. Is there a way to render a specific project based on its unique ID? { “projects”: [ { "id": 1, "picture": "portf.jpg" }, { ...

Managing State in a React Drawer Interface

One day, I decided to create a page with a Sidebar on the left, an Appbar at the top, and a content area. Initially, everything functioned seamlessly as one enormous component. However, as we all know, React's charm lies in breaking down various eleme ...

Transmitting OfficeJS 2D Array via an Ajax Call

Struggling with sending a "large" table using OfficeJS: functionfile.html loaded from manifest route <script> (function (){ "use strict"; Office.initialize = function (reason) { $(document).ready(function() { $("#send-data-button").cli ...

Creating an array of items in an HTML template to generate a PDF using Node.js

In my current project, I am utilizing html-pdf for creating PDFs. I have successfully generated all the necessary details in the PDF, however, I am facing an issue with creating a list of items from an array in HTML, which is required for the PDF convers ...

Converting MSK time to SST time using JavaScript: A Handy Guide

My API returns time in the format: 07:00 PM This timestamp is based on MSK (Moscow Standard Time) and I need it converted to SST (Singapore Standard Time) using either JavaScript or an npm package. ...

In order to utilize Next.js with pkg, you must enable one of the specified parser plugins: 'flow' or 'typescript'

Utilizing next.js with the pkg in my project, following the steps outlined in this tutorial, I encountered an error when running the pkg command: > Error! This experimental syntax requires enabling one of the following parser plugin(s): 'flow, t ...

Is there a way to create a footer that seamlessly integrates with the borders of a website?

I've been struggling to design a footer for my class website project. The problem is that the footer either overlaps the borders of the site or the text inside the footer goes under the border. I've tested several different footers, but none seem ...

Accessing deeply nested JSON objects in AngularJS

I've been working on an AngularJS single page application and I have successfully fetched files from a JSON. var app = angular.module("MyApp", []); app.controller("TodoCtrl", function($scope, $http) { $http.get('todos.json'). success ...

Unable to initiate the server in a new window due to the absence of a specified terminal application

When incorporating an external library into my React Native project, the installation process is usually smooth. However, when I try to integrate the library into my entire project and run 'react-native run-android' command, it shows an error. I ...

Leverage the Nuxeo client SDK with Angular 6 for seamless integration with RESTClient in

Looking to integrate the Nuxeo ClientSdk with my Angular 6 client to consume its REST API, but facing issues due to the lack of typescript definitions for this JavaScript package. Tried importing the library into my project using the following code snippe ...

Implementing dynamic attribute id addition to select option

Here's the code snippet I'm currently working with: Included HTML <select id="drop_opts"> <option>1<option> <option>2<option> <option>3<option> </select> ...

Sorting arrays in JavaScript can become tricky when dealing with arrays that contain values from two different arrays

When working with two arrays in JavaScript that are received from PHP, I combine them into a single array. Each element in these arrays contains a created_at value (from Laravel), and I want to sort these elements by their created_at values. The issue ari ...

Fixed navbar at the bottom of the page that transitions to static when scrolling reaches a certain location

Is it feasible to achieve this using Bootstrap v3? After conducting extensive research, it appears that a custom solution may be necessary. In essence, I am working with a navbar positioned at the bottom of the content area. Upon page load, if the navbar& ...

Exploring the possibilities of utilizing a Kendo grid within an ASP.NET Web API

I am currently using the open source edition of Kendo Web with the Kendo UI Web on ASP.NET MVC 4. My Kendo grid contains the following JavaScript code: <script> $(document).ready(function () { $("#grid").kendoGrid({ dataSource: ...