Michael Schwartz Michael Schwartz - 7 months ago 20
Javascript Question

If values are the same update code

http://liveweave.com/R9jW9x

I have 4 textbox's each representing a css padding location (ex. padding-top, padding-left, etc:)

I'm experimenting with value detections. What I'm trying to figure out is when padding top and bottom

[A]
are the same values (as well as left and right
[B]
) how to set the values to
padding: A B
;

If all are same to set value to
padding: A;


If all are different set value to nothing/blank

and

If all are different, or A & B maybe same, but C and D maybe different then to set value to
padding: A B C D;


The script works fine onload, but when the input values are changed my result is not finalizing.

Can anybody explain why this is?

$(document).ready(function() {
var top = $(".padding-top").val(),
bottom = $(".padding-bottom").val(),
left = $(".padding-left").val(),
right = $(".padding-right").val(),
result = $(".padding-final");

// Update padding code
var Finalize = function() {
if ((top === "") && (right === "") && (bottom === "") && (left === "")) {
// Check if all are empty
result.val("");
} else if ((top === right) && (bottom === left)) {
// If all are same
result.val("padding: " + top + "px;");
} else if ((top === bottom) && (left === right)) {
// Check if first two values are same
result.val("padding: " + top + "px " + left + "px;");
} else {
result.val("padding: " + top + "px " + right + "px " + bottom + "px " + left + "px;");
}
};

// Update padding code when sides change
$(window).on('load keyup change', function() {
Finalize();
});
});

Answer

I won't write the code for you. But, I will hopefully send you in the right direction:

First, you should check whether padding-top, padding-right, padding-bottom, and padding-left are equal to each other.

>> If they are equal, then you can set the middle one equal to any of the values (since they're equal).

>> If they are not equal, then you can check to see if top and bottom are equal to each other && left and right are equal to each other. If they are, then you can set the middle to the top/bottom number + " " + left/right number.

>> Else set the middle to top number, right number, bottom number, left number.


EDIT

Actually, I got to tinkering a bit with the idea and came up with this to help you a bit more. But, that's it. No more help from me!

var top = 2;
var bottom = 2;
var right = 5;
var left = 5;

top == bottom && right == left && top == left ? alert(top) 
    : top == bottom && right == left ? alert(top + " " + left) 
        : alert(top + " " + right + " " + bottom + " " + left);

JSFiddle


After you solve this, a more challenging problem would be to type numbers into the middle box and change the top/right/bottom/left paddings accordingly.