Discovering a CSS value using jQueryUncovering the CSS value with jQuery

Currently, I have a script that allows me to change the color of an event in a calendar to red when clicked.

 eventClick: function(calEvent, jsEvent, view) {
   $(this).css('border-color', 'red');
 }

Now, I want to enhance this feature by enabling the user to cycle through different colors with each click, starting from red and moving to green, then blue, yellow, etc.

     eventClick: function(calEvent, jsEvent, view) {
       if current color is red, change to green;
       else if current color is green, change to blue;
       etc.
 }

Essentially, I need to determine the current color and switch it accordingly among a set of predefined colors, which will be limited to about 5 options.

Answer №1

To accomplish this task, follow these steps:

$("#id").css("border-left-color")

The code snippet above will result in an empty string being returned.

$(this).css('border-color');

The border-color property is a shorthand for setting the individual properties of border-top-color, border-right-color, border-bottom-color, and border-left-color. In order to retrieve the border-color value, you must specify a particular side. For example, to retrieve the border-left-color, use $("#id").css("border-left-color"). This method should work fine assuming all sides have the same color.

Answer №2

In order to retrieve a value without setting it, you can use the same function call as the setter:

$(this).css('border-color');

If you need more information on this method, you can visit http://api.jquery.com/css/

It's important to note that the returned value from the getter may not always match your expectations. According to the documentation:

The computed style of an element might differ from the specified value in a stylesheet. For instance, dimension styles are typically in pixels though they could be em, ex, px or %. Different browsers may return CSS color values that are technically equivalent but not identical, such as #FFF, #ffffff, and rgb(255,255,255).

To avoid issues with getting incorrect values, it is recommended to assign colors to specific classes and then manage them accordingly.

For a practical example, check out @zzzzBov's demonstration on jsFiddle: http://jsfiddle.net/cT3c5/

Answer №3

Here is a quick way to retrieve a CSS property from an element:

const box = document.querySelector('.box'),
style = window.getComputedStyle(box),
background = style.getPropertyValue('background-color');

Try it out on JSFiddle!

Answer №4

I suggest entrusting all styling tasks to CSS. Utilizing toggling classes instead of setting inline styles via JavaScript is a more effective method for modifying styles, as it allows you to make changes without affecting the JS code.

It would be ideal to delegate the event handler in order to use different callbacks for various selectors.

If you are limited to using the same callback, you can still switch between classes by checking the state within the click callback:

eventClick: function(calEvent, jsEvent, view) {
    var $this,
        add;
    if ($this.is('.a')) {
        add = 'b';
    } else if ($this.is('.b')) {
        add = 'c';
    } else {
        add = 'a';
    }
    $this.removeClass('a b c').addClass(add);
}

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 way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

What is the best way to display just one record that has the lowest score out of all the records?

I need help with displaying only 1 record from the DL list that has the lowest score, instead of showing all records. In the example on stackblitz, you can see that for the first record, the DL scores are: 54, 20, and updated. Instead of displaying all 3 ...

Tweaking the placement of the dropdown menu in the subnavigation area

Just getting back into coding after a long hiatus - I've dabbled in the past but it's been about 6 years since I've worked with any code. Currently, I'm working on replicating a website for practice. I have created a nav bar and a drop ...

Utilizing a checkbox within a select dropdown component in Vue

Has anyone come across a checkbox dropdown feature in Vue? I have been searching online but couldn't find any examples or resources related to this. If someone has a working skeleton for it, please share! ...

"Mastering the Art of Combining Two AJAX Requests Seamlessly (Without the Need for Plugins

I currently have 2 distinct ajax requests: One for endless loading The other for product filtering - by size, color, orderby, and it functions correctly with pagination. However, after applying the filters, the loadmore script does not work as expecte ...

Font rendering issue in Chrome extension

I have been diligently following various tutorials on incorporating a webfont into my Chrome extension, but unfortunately, none of them seem to be working for me. Despite all my efforts, the font remains unchanged and still appears as the default ugly font ...

How to Delete an Element from a JSON Array in Scala

I received a JSON response that looks like this: [ { "id": 2202, "name": "name one", "phone": "+62888888", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98fbedebecf7f5fdead8fff5f9 ...

How can I update the value of a span element that was added to the HTML document through an AJAX request?

When a modal is triggered on click, data is added to it through an AJAX request to a PHP file. After the AJAX call, I want the values in span elements within the modal to change simultaneously with the input field of the modal. I attempted this JavaScript ...

Is it possible to use CSS to target the nth-child while also excluding certain elements with

How can I create a clear break after visible div elements using pure CSS? Since there isn't a :visible selector in CSS, I attempted to assign a hidden class to the div elements that should be hidden. .box.hidden { background: red; } .box:not(.hid ...

Create a single line of content for a carousel display

Seeking a solution where I can have a container that slides sideways without stacking in rows, I have exhaustively searched for answers using different keywords like single row, inline, flexbox, and grid but to no avail. Any assistance will be highly appre ...

I am curious if there is a wysiwyg web editor extension specifically designed for VS2010 available?

In my experience, I have been working with C#, HTML coding using VS2010 and MVC. Utilizing VS2010 has proven to be an invaluable tool for me in this process. Currently, I find myself needing to create some straightforward static web pages. I am wondering ...

Mastering the art of transmitting and receiving Json data

I need to establish communication between a client (built on xamarin.android) and a server (asp.net web forms). The goal is to send a JSON POST request from the client to the server in order to update the database. While I have managed to create and seri ...

npm encountered an error or issue during the installation process

I have configured my proxy settings in the .npmrc file, but I am encountering errors when running the npm install command: $ npm install npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program File ...

What is the best way to iterate through JSON objects stored in a single location?

Currently, I am dealing with a single JSON object structured as follows: Object --> text --> body --> div Array[20] --> 0 Object --> text --> body --> div Array[20] --> 1 Object --> text --> body --> div Array[20] --> . ...

Dynamic Next.js Redirects configured in next.config.js

After building the project, I am looking to update Redirects routes. Currently, we have redirect routes on our BE Api. My goal is to fetch these redirect routes dynamically and implement them in next.config.js. Here is what I have attempted: const getUrls ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Using Jquery to find the class that matches the current element

Is it possible to select a specific div by its class when there are multiple divs sharing the same class and triggering the same function on button click? I only want to target the class where $(this) is located. I've experimented with .parent, .chil ...

Updating the input value in a React application

With a list and an edit button, upon clicking the edit button, a new modal opens. How can I auto-populate the selected username email? The server-side response is {this.test.name}, where I provide him with the input value to auto-populate. However, when ...

What causes the slash URL to behave differently than other URLs when running through the middleware of NodeJS?

When I type http://localhost:3000/product into the browser, why do I see output for both '/' and '/product'? Take a look at this code snippet below. const express = require('express'); const app = express(); // http://loca ...

Using jQuery to load an image into a div and smoothly fade it in

I am currently working on creating a gallery and I am facing an issue with loading an image into a div. The problem arises when I try to apply a fade effect after the image has finished loading. If I remove the display:none property, the image does load in ...