If the background color is blue, then element class will be added

Currently exploring the realm of JavaScript, I am tackling a challenge with adding a class to an element based on its background color. Specifically, I aim to add a class to elements with a background color set to rgb(32, 44, 62). However, my current implementation applies the class to all elements, not just those with the specified background color. I have shared a test of the code below and any insights would be greatly appreciated.

https://codepen.io/tyearyean/pen/PoWvLwO

var basicBGColor = $('section.content_basic').css('background-color');

Javascript

    var basicBGColor = $('section.content_basic').css('background-color');

    $('section.content_basic').each(function() {
      if (basicBGColor == 'rgb(32, 44, 62)') {
        $(this).addClass('goldBorder');
      };
    });

Answer β„–1

It is important to include the following code inside the each loop:

var basicBGColor = $('section.content_basic').css('background-color');

This will ensure that the variable is executed within the loop, allowing for the condition

if (basicBGColor == 'rgb(32, 44, 62)')
to be evaluated correctly for each element in the loop.

To update your code, make sure to follow this structure:

 

    $('section.content_basic').each(function() {
      let basicBGColor = $(this).css('background-color');
      if (basicBGColor == 'rgb(32, 44, 62)') {
        $(this).addClass('goldBorder');
      };
    });

Answer β„–2

Even though I'm relatively new to Javascript as well, I highly recommend using (===) instead of (==) when checking for equivalence.

For example, instead of:

(basicBGColor == 'rgb(32, 44, 62)')

Consider using:

(basicBGColor === 'rgb(32, 44, 62)')

Answer β„–3

After the current code is executed, it applies the changes to all elements that match the criteria, not just the ones with the specified background color.

If you want to target individual elements, you need to specifically retrieve the background color of each element as shown below:

$('section.content_basic').each(function() {
  const basicBGColor = $(this).css('background-color');
  const isMatching = basicBGColor == 'rgb(32, 44, 62)'; 
  isMatching && $(this).addClass('goldBorder');
});
.content_basic {
    max-width: 100%;
    background-repeat: no-repeat;
    background-size: 100%,auto;
    position:relative;
}
.goldBorder:after{
    position: absolute;
    content: '';
    top: 20px;
    bottom: 20px;
    right: 20px;
    left: 20px;
    background: transparent;
    border: 1px solid #a48147;
    z-index: 0;
    pointer-events: none;
}
.goldBorder .body-content {padding: 2.5rem;color:#fff;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
  <body>
    <div id="main-content" class="">
  <section style="background-color: rgb(32, 44, 62);" uk-scrollspy="cls:uk-animation-slide-bottom-small;offset-top:50;delay:200" class="content_basic">
    <article style="padding:5% 0;" class="uk-padding-large uk-padding-remove-left uk-container uk-padding-remove-right interior">
                                <div class="uk-grid uk-grid-stack" uk-grid="">
                                                                                                    <div class="uk-flex uk-flex-center uk-width-1-1@m uk-first-column">
                            <div class="uk-light body-content">
                                
                                <h2 style="color: rgb(164, 129, 71);">Title</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis posuere leo eu sem mollis, et porta leo pretium. Morbi placerat placerat auctor. Vestibulum egestas nisl eget efficitur dictum. Cras commodo arcu libero, at scelerisque nulla semper ut. Praesent sed massa finibus nisi posuere ultrices. Cras imperdiet imperdiet enim, vel fringilla nunc ultricies non. Aliquam laoreet cursus urna id fermentum. Nullam magna nisl, sodales vel semper sed, lobortis vel ante. Proin volutpat at neque a maximus. Mauris sit amet rutrum nulla. Sed vel eros ut lacus interdum mollis et ut eros.</p>                                
                            </div>
                        </div>
                                                </div>     
         
    </article>
</section>

<section style="" uk-scrollspy="cls:uk-animation-slide-bottom-small;offset-top:50;delay:200" class="content_basic">
    <article style="padding:5% 0;" class="uk-padding-large uk-padding-remove-left uk-container uk-padding-remove-right interior">
                                <div class="uk-grid uk-grid-stack" uk-grid="">
                                                                                                    <div class="uk-flex uk-flex-center uk-width-1-1@m uk-first-column">
                            <div class=" body-content">
                                
                                <h2 style="text-align: center;">Title</h2>                                
                            </div>
                        </div>
                                                </div>     
         
    </article>
</section>
</div>
  </body>
</html>

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

Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issu ...

Concealed checkbox value in jQuery

I have a problem with setting the hidden checkbox "marketingPhone" to TRUE when the "marketingAAA" checkbox is checked as true. This part works fine. However, if any other checkbox on the page is set to TRUE, then it also sets "marketingPhone" to TRUE. I ...

Using a button click to toggle the vue-ctk-date-time-picker in VueJS

Currently, I am utilizing the Vue component - https://github.com/chronotruck/vue-ctk-date-time-picker within my own component. However, I am encountering an issue where I would like to maintain the component's original functionality while having a but ...

Implementing a Modal Based on Valid Input

I'm currently developing a journal book app using Flask and Bootstrap 5. One of the features I'm working on is a deletion feature, where users can input the number of records they want to delete. I want this feature to display a confirmation moda ...

Arrange ten objects in each of the four JavaScript arrays in ascending order based on a specific value

model with sample data -> [{ date: '13413413', name: 'asdfasdf', other: 'kjh' }] The getJSON function returns 4 arrays, each containing 10 model objects. array1 = 10 resultsObj sorted by date from newest to o ...

Having trouble viewing objects' content in the JavaScript console in Visual Studio 2015?

In the past, I was able to see all the content of my JavaScript objects like this: However, for some reason now, the content is not being displayed at all: I am using Visual Studio 2015 Community with Cordova and Ripple emulator. I have tried creating a ...

Unchecking and checking the radio button is necessary in order for it to function properly

Today, I'm puzzled by the odd behavior of my radio buttons in a pixel drawer project. In order for the radio button to function properly, I have to uncheck it and then recheck it. The pixel drawer allows me to change colors and sizes using these radio ...

Encountered an invalid prop type error while employing CSSTransition

Encountering an issue with the implementation of CSSTranstion for React. The purpose is to animate the mobile menu in a small application. Everything was functioning properly until the inclusion of the react-transition-group package, specifically using < ...

Reorganize divisions using Bootstrap

I am exploring different ways to manage responsiveness through the reordering of divs. While I am aiming for a solution that is highly flexible, any suggestion would be appreciated. Desktop View: https://i.stack.imgur.com/boSOa.png Mobile View: https:// ...

Ways to refresh a webxr session while clearing all models from the scene

Whenever the webxr session restarts, I notice that two instances of previous objects appear on the screen. I want the screen to be clear when the session restarts. Currently, I am using the following code: for( var i = scene.children.length - 1; i >= 0 ...

Refresh the webpage when using the browser's back or forward button in AngularJS with ui-router

In my AngularJS app, I have configured the ui-router state as follows: $locationProvider.html5Mode(true); $stateProvider .state('index', { url: '/index?zoom&center', views: { ...

Incorporating a text box underneath the model image

My application currently utilizes a grid gallery that perfectly fits my needs. However, there are two specific changes I need to make in order for it to be complete for my purpose. Unfortunately, I am struggling to figure out how to implement these changes ...

When attempting to execute an npm command, an error is encountered stating that chunk.sortModules is

It’s time to bring back an old project and make some modifications. I tried using git checkout 0.0.2 since that's the tag currently running on production, but it seems to be causing issues. After downloading the code to my PC, I removed the node_mo ...

Creating interactive JavaScript elements that can be moved around within a container

I recently faced a challenge while attempting to make draggable elements within a div. The issue arose when I realized that I couldn't figure out how to drag each element individually without affecting the others. My current code only allows for handl ...

I understand the reason behind the unexpected { token error, but I'm unsure of how to resolve it when my PHP script needs to transmit a collection of data to JavaScript

I am currently utilizing this JavaScript fetch code to retrieve data from PHP async sendRequest(selectValue=this.selectValue){ const fetchResponse = await fetch('/server/getLastWords.php?select='+selectValue); const fetchJSON = await fe ...

Magnific Popup is causing a glitch in my Ajax cart slider, preventing my code from functioning properly

Currently, I have implemented an Ajax cart slider that slides from right to left whenever an item is added to the cart. Customers are given the option to add a product with an image to their cart and can view the image directly from the cart by clicking on ...

Guide on extracting nested JSON data values using JavaScript

{ "_id" : ObjectId("587f5455da1da85d2bd01fc5"), "totalTime" : 0, "lastUpdatedBy" : ObjectId("57906bf8f4add282195d0a88"), "createdBy" : ObjectId("57906bf8f4add282195d0a88"), "workSpaceId" : ObjectId("57906c24f4add282195d0a8a"), "loca ...

What is the best way to format specific text as bold within an input text field?

I am attempting to make certain text bold within an input text field. However, I'm uncertain about how to achieve this because HTML code is not recognized inside a text field. Therefore, using <b> will not be effective. Is there a way to bold sp ...

Menu with hover functionality in JQuery that functions as a standard menu even when JavaScript is disabled in the browser

Is it possible to modify this code so that the hover point links' images do not appear if the browser has JavaScript disabled? And can the links function like a regular hover point even when JavaScript is disabled? <script type="text/javascript" s ...

submit the JSON formatted data to the server

I am attempting to extract data from a form and transmit it to a remote server: Below is the code snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> ...