-3

with JQuery how would you change a CSS property like (in this example from left to right) I found that .css("left") could be used to retrieve the value, then I could write a function to set the .css("right"), but is there an easier (more compact) way to do it ?:

#set { left: 400px; bottom: -200px; }

to

#set { right: 400px; bottom: -200px; }

Thanks

2
  • possible duplicate of How to define multiple CSS attributes in JQuery? Commented Mar 18, 2014 at 12:31
  • ok guys thanks for the downvotes, I maybe didn't explained my point correctly... I didn't want to use Avempace's solution with addClass and removeClass (because I have a bunch of #set (#set1 to #setxx) and didn't want to duplicate the values). Felix's solution corresponds to what I was looking for. Commented Mar 18, 2014 at 12:45

4 Answers 4

5

Use classes and change the class.

You can find how in the question jquery change class name

so your css will look like:

.set_left { left: 400px; bottom: -200px; }
.set_right {right  400px; bottom: -200px; }

With jquery you just change the class.

$("#set").removeClass('set_right').addClass('set_left');

or

$("#set").removeClass('set_left').addClass('set_right');
Sign up to request clarification or add additional context in comments.

Comments

4

You can use .css()

var left = $('#set').css('left');
$('#set').css({
    right : left,
    left: 'auto'
});

1 Comment

Better to use auto as the initial value of left property. Using left: 0 may expand the absolutely positioned elements horizontally.
1

To Read

$('object').css('CSSKEY')

To Write

$('object').css('CSSKEY','NEW VALUE)

http://api.jquery.com/css/

Your alternate method as suggested, is to use .AddClass and .RemoveClass - It provides a cleaner markup

http://api.jquery.com/addclass/
http://api.jquery.com/removeclass/

Comments

0

JSFiddle Demo

You could do something like this:

$("#set").css({"right" :  0, "left" : "auto"});

Alternativley, you could use addClass, and set the styles in the CSS, and using jQuery, just call addClass("your-class")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.