Reputation: 759
This is probably quite simple but I can't figure it out. I want to use jquery to add padding-top to a div in addition to it's original padding-top. My code so far is:
var headH = $('#header').outerHeight();
var mastPad = $('#masthead').css('padding-top');
$('#masthead').css('padding-top', mastPad + headH);
This results in huge amounts of padding I presume because JQuery keeps multiplying the padding. I need to find a way to grab the original padding-top and then add to it.
Thanks
Upvotes: 2
Views: 2772
Reputation: 1074028
$('#masthead').css('padding-top')
returns a string, not a number, so it could be that headH
is being appended to that string, not added to its numeric value;
Perhaps:
$('#masthead').css('padding-top', parseInt(mastPad, 10) + headH);
parseInt
will parse what it can find, and then ignore the rest. So "42px"
becomes 42
(whereas using a unary +
or Number
will choke on the px part).
Here's a self-contained example, replicates the problem for me on Chrome with the with
div and not the without
div:
setTimeout(function() {
var top;
var $without = $("#without");
top = $without.css("padding-top");
snippet.log("top = [" + top + "] (type: " + typeof top + ")");
$without.css("padding-top", top + 100);
var $with = $("#with");
top = parseInt($with.css("padding-top"), 10);
snippet.log("top = [" + top + "] (type: " + typeof top + ")");
$with.css("padding-top", top + 100);
snippet.log("Updated");
}, 2000);
div {
padding-top: 20px;
border: 1px solid #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="without">We'll update this div without <code>parseInt</code></div>
<div id="with">We'll update this div with <code>parseInt</code></div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
I'm a bit surprised that "20px100" ends up being a really big pad, but...
Upvotes: 6
Reputation: 9567
You can store that variable in the global context and then protect it from incrementing, like so:
var originalPad;
var ranOnce = false;
function GrowPadding() {
var headH = $('#header').outerHeight();
if(!ranOnce) {
mastPad = parseInt($('#masthead').css('padding-top'), 10);
ranOnce = true;
}
$('#masthead').css('padding-top', mastPad + headH);
}
Upvotes: 0