Comparing background-color using .css() in jQuery/Js

I've been experimenting with creating angled divs on a webpage, where each basic panel is separated by an angled break. The idea is to have the background-image of one div flow smoothly into the background-color of the next div.

Since I couldn't directly select pseudo classes, I opted to use .addClass() in jQuery to toggle the presentation of the angles. However, I've run into some issues with my comparisons - either all the divs turn green or they all get angles added to them. It seems that my approach may be flawed, and I'm struggling to pinpoint where I'm going wrong.

Below is the JavaScript and jQuery code I've been working on:

$(function() {
     green = $('div').css("background-color", "rgb(0,255,0)");
          if ($('.box').prev() === green) 
        {
          $(this).addClass('withTop withoutTop');
          //if ($(this).css("background-color") == green) 
        }
    });

I even tried using regex to extract only the digits from the RGB values, but it hasn't made much of a difference. Any help would be greatly appreciated! Here's the link to the codepen for reference: http://codepen.io/AnomalousDevs/pen/GJmrrw

CSS and markup

$(function() {
  green = $('div').css("background-color", "rgb(0,255,0)");
  if ($('.box').prev() === green) {
    $(this).addClass('withTop withoutTop');
    //if ($(this).css("background-color") == green) 
  }
});
.box {

  height: 100px;

  width: 100%;

  /*background-color: rgb(0,255,0);*/

  position: relative;

}

... (CSS continuation) ...

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="parent">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box withTop"></div>

</section>

Answer №1

It seems like your question is a bit unclear, but if I understand correctly, you want to add a class to the .box following the green one.

Here is a basic logic suggestion for achieving this:

$(function() {
  var boxes = $('.box'),
    greenBox = '';
  // Loop through each box
  boxes.each(function(index) {
    // Check if this box is the green one
    if ($(this).css("background-color") === "rgb(0, 255, 0)") {
      greenBox = $(this);
      // Add class to the next box
      $(this).next().addClass('withTop');
    }
  });
});
.box {
  height: 100px;
  width: 100%;
  /*background-color: rgb(0,255,0);*/
  position: relative;
}
.box:nth-of-type(5) {
  background-color: green;
  /* background-image:url("http://www.google.com/imgres?imgurl=http://dreamatico.com/data_images/guitar/guitar-6.jpg&imgrefurl=http://dreamatico.com/guitar.html&h=851&w=1280&tbnid=DVUGPDoyiOu4sM:&zoom=1&docid=OlLKDKDUUigDoM&hl=en&ei=iqJzVcaEOcvAtQXW-oO4Cw&tbm=isch&ved=0CDwQMygKMAo");*/
}
.box:nth-of-type(4) {
  background: red;
  position: relative;
}
.box:nth-of-type(3) {
  background: blue;
}
.box:nth-of-type(2) {
  background: rgb(0, 255, 0);
}
.box:nth-of-type(1) {
  background: lightblue;
}
.withTop::before {
  content: '';
  position: absolute;
  background: black;
  width: 100%;
  /*top:-16px;*/
  height: 30px;
  left: 0;
  transform: skewY(-1.3Deg);
  z-index: 1;
}
.withoutTop::after {
  content: '';
  position: absolute;
  background: black;
  width: 100%;
  height: 30px;
  left: 0;
  transform: skewY(2Deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="parent">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box withTop"></div>
</section>

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

When navigating through a view in backbone.js, ensure to include an argument in the routing process

Looking to include an argument while routing within a Backbone.js application Below is the script: var AppRouter = Backbone.Router.extend({ routes: { 'toolSettings/(:action)' : 'toolSettings' } }); var initialize = function ...

Prevent the event from bubbling up on active elements

Having trouble with stopping event propagation? Picture this situation: <table id="test"> <tbody> <tr> <td class="row"> </td> <td class="row"> </td> <td class="ro ...

Enhance Your Media Gallery with Filters

After implementing a media gallery on my website using this resource: http://tympanus.net/Development/MultiMediaGallery/, I encountered an issue. While the gallery functions perfectly within my Wordpress installation, I wanted to enhance it by incorporatin ...

The spawn function in the child_process module throws an error with the code -2, specifically the

Hey there, I'm working on creating an npx command that allows me to run child commands within my package.json bin: "bin": { "malzahar": "./src/bin/malzahar.js" }, Below is the code from my malzahar.js: #! /usr/bin/en ...

Discovering applied styles based on component props in Material-UI v5 using browser developer tools

When working with Material UI v4, I found it easy to identify which styles are applied by component props classname using browser dev tools. This allowed me to override specific styles of the component effortlessly. However, in Material UI v5, I am unsure ...

I have been tirelessly attempting to resolve this issue, yet all my efforts have proven futile thus

Encountering an issue with web packs and nextjs. import NextDocument, { Html, Head, Main, NextScript } from 'next/document' import theme from '../libs/theme.js' export default class Document extends NextDocument { render() { retu ...

Authenticating with Google using a Custom Application Title

My website currently requires Google+ authentication in the following way - However, I want to revamp it to resemble stack overflow's method - Here are two necessary changes - 1) Replace This app with My App Name 2) Include only View your email ad ...

Execute HTML code within a text field

Is it possible to run html code with javascript inside a text box, similar to w3schools.com? I am working solely with html and javascript. Thank you. For example, I have two text areas - one for inserting html, clicking a button to run the code, and displ ...

struggling to access $scope variable in MVC partial view using AngularJS

I am looking to include a partial in my main content. This snippet is from my _layout.cshtml page. <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.T ...

Maintaining Image Aspect Ratio within a Div with a Specified %width

Apologies for the repeated question, but my research hasn't yielded a solution I can apply. Inside a div with the specified styles, there is an image: <div class="thumb grid_6"> <img src="img/test2.jpg" alt="flavin" /> </div> . ...

When defining a component decorator in Angular 2, mixing tabs and spaces can lead to an unhandled exception

After refactoring my Angular 2 component code and adding some tabulations, the code suddenly stopped working. Surprisingly, when I removed the tabs (spaces), it started working again. @Component({ templateUrl : './app.component.html', styl ...

What is the best way to extract information from a dynamically generated bootstrap form with changing fields and names?

In my MERN app, I have implemented a Bootstrap form where users can input various martial arts styles such as judo and bjj. React-tag-component is used to manage these styles. As users enter their preferred style, it gets added to an array named selected. ...

In a set of strings, locate the two shortest ones, remove them, and then add them back to the end repeatedly until there is only one string

I've been struggling with a coding challenge for a couple of hours now and could really use some help. Here are the detailed instructions: Take an array of strings and create a single string by following these steps: Repeat the following steps as lo ...

Is your blockui overlay failing to cover the entire page?

I have implemented blockui to display a "Wait ... loading" popup on my webpage. It is mostly working fine, but I am facing a small issue where the overlay does not cover the entire width of the scroll window when I scroll right (although it covers the full ...

React Native is facing difficulty in fetching pagination data which is causing rendering errors

Currently, I am working on fetching pagination data from an API. The process involves retrieving data from https://myapi/?page=1, then from https://myapi/?page=2, and so on. However, despite following this logic, I encountered an error that has left me puz ...

What is preventing me from utilizing require in vue-router's routes.js file?

Vue-router typically requires the standard setup as outlined below: In main.js, the routes.js file is required and it usually contains code similar to this: //routes.js import Register from './components/Register' import Login from './comp ...

Implementing the rotation of an element using 'Transform: rotate' upon loading a webpage with the help of Jquery, Javascript, and

A div element designed to showcase a speedometer; <div class="outer"> <div class="needle" ></div> </div> The speedometer animates smoothly on hover; .outer:hover .needle { transform: rotate(313deg); transform-origin: ce ...

Convert an HTML table into an Excel file using PHP

After successfully generating DATA from PHP into an HTML table format, I utilized the code below to export it to EXCEL: header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="BASIC_Data.xls"&apos ...

Access remote web page within bootstrap modal

Dealing with a recurring issue, I am trying to create a modal that opens content from a remote page populated by a MySql database. Custom styling is also required for the modal. Progress has been made, but now I'm stuck. Below is the current code: Ou ...

Parsing JSON data in JavaScript to extract multiple records and store them in individual variables in memory

Although I have utilized JSON stringify and JSON Parse before, I am currently struggling to split up my JSON result into multiple variables. Challenge: My JSON result contains multiple sections or pages, and my objective is to store each of these results ...