Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass variables to jquery's css function?

I'd like to set css of a div element dynamically using jQuery css() function instead of using string literals/ string constants for the css() function. Is it possible?

Instead of using the following codes with string literals:

$('#myDiv').css('color', '#00ff00');

I would like to use variables to set css for #myDiv element like

Version 1:

var propertyName = get_propery_name(myVariable1); // function get_propery_name() returns a string like 'background-color'
var value = get_value(myVariable2) ; //  function get_value() returns a string like '#00ff00'
$('#myDiv').css(propertyName, value);

Version 2: (just hard coded to see if they work without calling custom functions like version 1 above):

var propertyName = 'background-color';
var value = '#00ff00';
$('#divLeftReportView').css(propertyName, value);

Both variable versions of codes do not work. Please help. Thanks.

like image 545
user1219702 Avatar asked May 16 '12 14:05

user1219702


Video Answer


2 Answers

Both of your examples will work just fine. I would suggest just a bit cleaner approach (personal syntax preference):

$(document).ready(function () {
    $('#myDiv').css(get_propery_name(myVariable1), get_value(myVariable2));
}

Here's a working fiddle.

If you want to take it a step further, you can return a CSS map instead of strings:

$('#divLeftReportView').css(GetCssMap("foo"));

function GetCssMap(mapIdentifier) {
    return { "background-color" : "#00ff00" }
}

Here's a working fiddle.

like image 53
James Hill Avatar answered Sep 19 '22 05:09

James Hill


The code you posted here should work. I have done both versions of what you are trying to do several times. If it is not working, there is a good chance that something is wrong somewhere else in your javascript OR that you do not have the correct selector/id for the element(s) which you want to change.

Try adding alert("test"); immediately after $('#divLeftReportView').css(propertyName, value);. If you get the popup saying "test" then the problem is with your selector. If not, then the problem is a bug in your javascript.

Also try adding $('#divLeftReportView').css("background-color", "#00ff00"); in the same place. That will confirm whether or not the selector is working.

like image 26
Jeffrey Blake Avatar answered Sep 21 '22 05:09

Jeffrey Blake