Search code examples
javascripthtmldynamicprototypejswidth

How can I test if an input's width was set manually?


HTML

<select id="food">
    <option>Pick Favorite Food</option>
    <option>Banana</option>
    <option>Orange</option>
</select>

<select id="place" style="width: 100px;">
    <option>Pick Favorite Place</option>
    <option>Disneyland</option>
    <option>Hawaii</option>
</select>

JavaScript

$('food').getStyle('width'); //56px
$('place').getStyle('width'); //100px

If no width is specified, the browser sizes the input to fit all of the text dynamically. Obviously this has to happen so you can see your elements.

Is there a way to test if the element was styled manually? Either inline, through a stylesheet, or even through JavaScript?

$('food').getWidth(); //false
$('place').getWidth(); //100px

Solution

  • Ryan has the right idea, but since you're using Prototype, you can use readAttribute('style') and trust that the return value came from the style attribute and not through a stylesheet.

    Here's a fiddle: http://jsfiddle.net/Q4bRP/

    Here's the fiddle's code:

    #my-div {
        border: 1px solid green;
        margin-bottom: 10px;
    }​
    

    -

    <div id="my-div">#my-div, click me</div>
    <button id="my-button">add inline style to #my-div</button>
    

    -

    $('my-div').on('click', 'div', function(event, el) {
        var styleAttrVal = el.readAttribute('style');
        if (styleAttrVal) {
            alert(styleAttrVal);
        } else {
            alert('no inline style set!');
        }
    });
    
    $('my-button').on('click', function(event) {
        $('my-div').setStyle({backgroundColor: 'yellow'});
    });​
    

    You can use a Regex on styleAttrVal to test for whatever inline value you're looking for.

    Edit: Regarding the last comment above on using a Regex to pull out what you need: You may have some luck looking through Prototype's source to find something you need. They must be doing something similar already for Element.getStyle to work that you may be able to leverage.