Josh
Josh

Reputation: 133

Javascript Image Padding

I'm trying to create a Tumblr theme, however I always run across this error if my image is not equal to 500 pixels in width and it is under, the text will run across the right of the page, as opposed to under.

I wanted to know if anyone knew how to create a script that would obtain the width value of an image within image id, and create a padding on the left and right side panes to equal to 500 px

I do not know javascript at all, so I'm just going to take a quick stab and brief up what i'd expect to happen

<script type="text/javascript">
document.onload
var a = document.getElementbyId('photo')
if a < 500 function d() ({
a = obtain image width
var c = (500 - (var a))/2
function e()(
{style.padding-right: (var c); style.padding-left: (var c);});
)};
</script>

I CLEARLY do not have knowledge in Javascript, so please forgive me for writing a brief excerpt of mumbojumbo but I just wanted to get a clearer vision of how to do this

I am okay with using jQuery.

Upvotes: 0

Views: 2474

Answers (2)

Cameron Askew
Cameron Askew

Reputation: 1413

I strongly recommend using jQuery when you plan on manipulating html elements regularly. Here's an example using jQuery.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $(function() {
        var $photo = $('#photo');
        var width = $photo.width();
        if (width < 500) {
            var padding = (500 - width)/2;
            $photo.css("padding-right", padding);
            $photo.css("padding-left", padding);
        }
    });
</script>

Upvotes: 2

random_user_name
random_user_name

Reputation: 26160

Since you are open to using jQuery, the following code should get you pretty close:

// Get the width of the photo
var width = jQuery('#photo').width();
// Only add padding if less than 500 wide
if (width < 500) {
    // Padding left / right should be half the difference
    var padding = (500 - width) / 2;
    // Apply padding to the photo
    jQuery('#photo').css("padding", "0 " + padding + "px");
}

Upvotes: 1

Related Questions