getButterfly Logo getButterfly code wrangling since 2005


My latest UI challenge was to position an element inside a variable width element, relatively positioned. The element had a background image which did or did not cover the entire width. White space was added to the left and right of the image.

My task was to get the background image width, get the parent element width, subtract the image width and divide it by 2 (left an right). Then, absolutely position the overlay element.

To further add to this challenge, the parent element was a slider. Slides had background images with various sizes, so I had to constantly check for the width, without allowing the overlaid element to constantly jump.

Got it so far?

I got jQuery to get the background image width with the following function:

function getImageWidth(which) {
    var img = new Image;
    img.src = $(which).css('background-image').replace(/url\(|\)$/ig, '');

    return img.width;

Then I checked for DOM ready and applied a CSS rule for right positioning:

    $('.thesticker').show(); // was previously hidden
    $('.thesticker').css('right', ($('#gallery').width() - getImageWidth('#gallery'))/2);
    setInterval(function() {
        var w = getImageWidth('#gallery');
        if($('.load').is(':visible')) { // this is the preloader spinner element // I'm using it to get the slide change
        else {
            $('.thesticker').css('right', ($('#gallery').width() - getImageWidth('#gallery'))/2);
    }, 0);

My overlaid element is .thesticker and the parent element is #gallery. I am checking every millisecond for a slide change (not good from a performance point of view, it can be optimized by injecting the check inside the slider script).

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply