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 hierarchy to be followed within the <head> element?

I have been developing websites using HTML for nearly 3 years now, but since I had to teach myself, there are still a few things I am unsure about. One question that has recently become important is whether it is possible to create groups within the <h ...

Parsing JSON with Jackson to deserialize Commons MultiMap

Looking to serialize and deserialize a MultiMap using JSON in Apache Commons 4. Here's a piece of code to test: MultiMap<String, String> map = new MultiValueMap<>(); map.put("Key 1", "Val 11"); map.put("Key 1", "Val 12"); map.put("Key 2" ...

Node.js UDP broadcast to subnet not working properly in Linux

Here is a simplified Node JavaScript code snippet for testing purposes. Click here to view the code on GitHub This code creates a socket for each interface address, calculates the subnet broadcast address, and then sends data every second for 4 seconds t ...

Issue when Updating Component State: React child cannot be an object

I'm currently in the process of familiarizing myself with React and how to manage component state. My goal is to build a component, set up the initial state using a constructor, make a GET request to the server to fetch an array of objects, and then ...

What is the best way to merge an array of objects into a single object?

Is there a way to dynamically convert object1 into object2, considering that the keys like 'apple' and 'water' inside the objects are not static? const object1 = { apple:[ {a:''}, {b:'&apos ...

Unlocking secure content with Ajax

Trying to access a webservice or webpage solely through ajax, as it is the only allowed method for some reason. The webservice is secured with corporate SSO. When requesting webpage X for the first time, you are redirected to login page Y, outside of the a ...

The scrollbar track has a habit of popping up unexpectedly

Is there a way to prevent the white area from showing up in my divs where the scroll bar thumb appears? The issue seems to occur randomly on Chrome and Safari. This is the div in question .column-content{ height:60vh; padding: 10px 3px 0 3px; overf ...

Is there a way to initiate an AJAX post request with the Authorization header for the initial request using Windows Authentication?

I'm working on a web application that has a video page and a Web API for logging purposes. The events are triggered using an ajax post request: function logAction(actionToLog) { $.ajax({ type: 'POST', url: "/api/v/" + cu ...

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

Is it advisable to substitute setTimeout with node-schedule in a node.js environment?

How can I prevent players from entering a raffle between 11:55pm - 11:59pm every Thursday? I attempted to use node-schedule to block access during this time frame by scheduling it to run every second, but unfortunately, I was still able to access the route ...

Make sure to always target a specific DIV element, regardless of whether any of its child divs are

I have a div named "box" nested inside another div called "container." When I click on the box, I am able to retrieve its ID perfectly. However, when I click on the container, I want to obtain the ID of the box instead of the container. Is there a way fo ...

Enhancing bar chart presentation with text in d3

Looking to enhance my bar chart by adding text tooltips that appear when hovering over each bar. While I am a beginner with d3, I've been struggling to implement this feature effectively. Despite trying various methods gleaned from online resources, t ...

A novel RxJS5 operator, resembling `.combineLatest`, yet triggers whenever an individual observable emits

I am searching for a solution to merge multiple Observables into a flattened tuple containing scalar values. This functionality is similar to .combineLatest(), but with the added feature that it should emit a new value tuple even if one of the source obser ...

Easily Update Your Div Content by Simply Clicking a Single Link/Button

I am in need of assistance here. My goal is to display dynamic content within a div. Below you will find the code I currently have: <script type="text/javascript"><!-- function AlterContentInContainer(id, content) { var container = documen ...

initiate scanning for HTTP GET calls

My current project involves using electron to create an application that serves multiple image files through a webserver using express. Another app built for Android is responsible for retrieving and posting files to this server. While I have successfully ...

The Angular UI Datepicker is not reflecting changes in scope variables within the dates-disabled function

I'm currently working with AngularJS and the Angular UI Bootstrap. I've encountered an issue that I initially thought was related to scope, then initialization, but now I'm stuck trying to figure out what's causing the problem. I' ...

Determine the yearly timetable by comparing it with the present date in MVC4

I'm looking for a way to calculate the annual date by considering the current date in an MVC project. Specifically, I want to display the date "2017/mar/24" in my textbox based on the current date. Do you know if there is any possible solution using C ...

Having numerous sections condensed into one cohesive page

Currently, I am working with backbone.js to develop a single-page application that takes inspiration from the functionality of trello.com. I am interested in learning how to display multiple pages on top of the original page and effectively structure the ...

Identifying shifts in offsetTop

In my design, I have a page where scroll bars are not allowed, meaning all content must be visible at once. The image below shows the basic layout of the screen to give you an idea. The layout consists of two blocks - Block 1 and Block 2. Block 1 is expan ...

Select a CSS design with C# coding in ASP.net

I have defined two classes in my embedded CSS on the Default.aspx page. If necessary, I can move the code to an external CSS file. Is it possible to write C# code that allows me to select between these two styles for my table after clicking a button? I ha ...