Troubleshoot: jQuery not applying CSS property stored in variable

Is it possible to set CSS properties using a variable, such as {background: red; }?

I tried implementing the code but encountered an error. Here is the link to the js fiddle for reference: js fiddle

Javascript

            var Key = 'background';
            var Value = 'yellow';


                $('.test').css({

                    Key: Value
                });

Answer №1

You should format it as .css("propertyname","value"). Therefore, your code will have to be altered to something like

$('.test').css(Key, Value);

For additional information, check out this resource

Answer №2

apply this code snippet:

$('.app').addClass(Name, Style);

See Demo

Answer №3

When it comes to applying CSS to an element using jQuery, there are two methods you can use:

Method One:

$(selector).css("propertyname","value");

Method Two:

$(selector).css({"propertyname":"value"}); // object with key : value pair

What seems to be the problem in your code?

The problem is

{Key:Value}

where the object key should actually be a string (""), which means that the first method would work better in your case:

$('.test').css(Key, Value);

To further understand this issue, check out this Fiddle

Answer №4

To utilize the plain object css overload effectively, follow these steps:

$('.test').css({
'background': Value
});

Alternatively

var properties ={};
var Key = 'background';
var Value = 'yellow';

properties[Key] = Value;

$('.test').css(properties);

The issue with {Key: Value} arises because it interprets the property name as Key instead of background.

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

What is the method for extracting style attributes from HTML using JavaScript?

Is there a way to extract only the applied CSS rules to a DOM node using JavaScript? I am familiar with getComputedStyle, but it retrieves all styles, not just those applied from stylesheets, inline styles, or injected into the CSSOM. The technique I hav ...

Implementing a django like feature using ajax requests

I am currently working on a template where I have a link for my article: <div id="voteUp"> <h4><a href="{% url "vote_up" article.id %}">Like {{article.up_vote}}</a></h4> </div> My goal is to increase the vote count for ...

Problems with Key Presses in Form Verification

Yesterday evening, our supervisor called me to report an issue with our app. He mentioned that when he tried to log in using a dummy password, the validation was successful. It seems that clicking on the mouse to authenticate the password was working corr ...

The delete button using jQuery Ajax is successfully working, however, the data is not being removed

I am having an issue with the delete button. It seems to be working fine as it displays 'record deleted successfully', but the record is not actually being deleted from the table and database. Below is the code I am using for the delete query: & ...

How can you compare two texts in Django and display a message based on their correctness or error?

As a newcomer to Django, my goal is to compare two texts between the frontend and backend and receive feedback on whether they are similar or different. These two texts are essentially short HTML codes. My primary focus is on the logic and code for compari ...

How can I update jQuery CSS method on resize event?

Having trouble vertically centering a div inside the body? I've come up with a jQuery function that calculates the ideal margin-top value for achieving perfect vertical alignment. Here's how it works: Obtain container height, Get child height, ...

Guide to inheriting and overriding text styles

I am looking for a way to customize the style of all h6 elements within reactjs/material-ui, without using themes. I have attempted the code below, among other methods: const useStyles = makeStyles({ someClass: { h6: { fontSize: &qu ...

IE11 not running Angular code inline as expected

Currently in the process of developing an AngularJS application, I came across a strange issue that I have never encountered before. It may be a simple fix, but I am unsure of the exact terminology to search for the right solution, so I apologize in advanc ...

Ways to retrieve anchor tag values from an AJAX response without a defined class

if(ajaxRequest.readyState == 4) { var response = ajaxRequest.responseText; response=response.split('^^--^^'); var buname=response[5].split('^^|||^^'); //rest code } The AJAX request has returned the following code, now stored in the va ...

Maintained grid column stability amidst various modifications

I have a complex 2-column grid layout, and the example shown here is just one part of it. The complete code follows a similar structure. I am looking for a way to ensure that the green box always stays close to the red box in the layout, without having a ...

To prevent the page focus from shifting, make sure to force click on a blank link

My question involves an empty link: <a href="#" id="stop-point-btn">+ add stop-point</a> This link is connected to a JavaScript function: $("#stop-point-btn").bind("click", addStopPoint); The JS function simply inserts content into a specif ...

Carousel displaying multiple cards with only one card visible per slide

I am currently using Bootstrap 5 to create a carousel with multiple cards, but I am facing an issue where only one card is displayed per slide. How can I modify it so that 3 cards are shown per slide? Should I utilize rows and columns for this purpose? A ...

AngularJS: Utilizing UI Bootstrap Popover with the Placement Set to 'bottom-right'

I am working with UI Bootstrap and AngularJS, attempting to customize a popover to have the 'bottom-right' placement instead of the default 'bottom' or 'right'. The desired functionality is illustrated in the image below. htt ...

Unable to execute a JavaScript function when triggered from an HTML form

This is the code for a text conversion tool in HTML: <html> <head> <title> Text Conversion Tool </title> <script type="text/javascript"> function testResults(form) { var str = form.stringn.value; var strArray = str.split(" ...

CSS: Centralize content and use a div to hide images that overflow the container

I successfully centered my divs and images both horizontally and vertically using CSS: .center { height: 100% } .center-center { position: absolute; top: 50%; left: 50%; width: 100%; transform: translate(-50%, -50%); text-align: center; ...

"Facing a dilemma with Javascript's Facebox getElementById function - not fetching any

Utilizing facebox, I am initiating a small modal dialog with a form and attempting to retrieve the value from a text field on that form using javascript. Below is the HTML code: <div id="dialog-form95" style="display:none"> <div class="block"> ...

Navigation bar links not leading to the correct corresponding pages

Whenever I try to access index.php, it loads perfectly the first time, but I encounter an issue when trying to navigate to another page from the index page. Error: Object not found! The requested URL was not located on this server. The link on the ref ...

Dropdown button split aligned with its first button

Comparing the alignment of split button dropdowns in Bootstrap 3 and Bootstrap 4, I find that Bootstrap 3 aligns them to the left of the first button, while Bootstrap 4 only aligns them according to the second button. https://i.stack.imgur.com/gAt78.png h ...

Troubleshooting a problem with CSS styling in a jQuery bounce effect

In my current project, I am experimenting with creating a unique 'hovering' link. When the user hovers over an image and then moves the mouse away, I want the link to 'jump' back instead of using jQuery animation. +-----------+ | I ...

The AngularJS ng-view was commented out and no errors were triggered

How can I utilize ng-view in AngularJS? I have created a folder named "detail.html" containing one HTML file. My goal is to load this file into the ng-view tag located in my index.html. However, despite commenting out ng-view, no errors are occurring. ...