pistacchio
pistacchio

Reputation: 58873

jQuery: actual div width

I have two <div>, one nested into the other defined like this:

<div class="wrapper">
    <div class="content">
        [..] Content [..]
    </div>
</div>

The css:

#div.wrapper
{            
    width: 660px;
    overflow: hidden;
    float: left;
}
#div.content
{
    white-space: nowrap;
}

The effect is what i want, the content lays down horizontally within the inner but is hidden when it exceeds, (i then scroll it with jQuery).

Since I don't know the content of .content (nor it is predictable), I need to know the real width of it (defined by the content), but both .width() and .innerWidth() give me the same result that is 660 when first called (like the container div) and 660 + x when I call it after having scrolled it by setting a negative margin-left (x is the left shift set with the margin).

How to get the real, content dependent width of the element? Thanks

Upvotes: 7

Views: 6492

Answers (4)

Willem Mulder
Willem Mulder

Reputation: 13994

Divs by default take full width in their parent, so width will always be the width of the parent.

If you don't want that, you would use

#div.content
{
    white-space: nowrap;
    display: inline-block;
}

or possibly

#div.content
{
    white-space: nowrap;
    float: left;
}

as to turn the #div.content element into an inline or float element respectively, which only takes up as much space as it needs (i.e. not necessarily all the space that the parent provides). So that should work!

Upvotes: 10

Aram Kocharyan
Aram Kocharyan

Reputation: 20431

I wasn't sure why you used #div.* since that would mean you have an element with id div. If you mean to specify a div with a certain class, use div.class-name. Since a div resides as a child inside another div, it takes its parent's width. Setting the float to left allows it to expand outside this limit.

div.wrapper {
    width: 660px;
    overflow: hidden;
    float: left;
}
div.content {
    white-space: nowrap;
    float: left;
}

Scrolling example: http://jsfiddle.net/9E8G7/6/

Here's a quick jQuery example I wrote, can be improved I'm sure. It scrolls until it reaches the end of the content.

$(document).ready(function(){
    var content = $('.content');
    var margin = 0;
    var scrollFunc = function() {
        margin--;
        content.css('margin-left', margin);
        var diff = content.width() - $('.wrapper').width();
        if (margin > -diff) {
            var scroll = setTimeout(scrollFunc, 10);
        }
    };
    scrollFunc();
});

Upvotes: 4

user191966
user191966

Reputation:

Did you try: jQuery.outerWidth(), I mean $(yourelement).outerWidth()?

Upvotes: 1

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

Have you tried element.offsetWidth?

Upvotes: 0

Related Questions