user2505665
user2505665

Reputation: 71

Jquery on resize apply parent width to child

How can I apply width of the li to the a ? This should happen on resize. So the a always have the li width.

http://jsfiddle.net/JCVnY/5/

var parentWidth = $('ul li').parent().width();
var $window = $(window);
$window.resize(function resize() {
    $('ul li').each(function () {
        if ($(this).closest('a').length == 1) {
            parentWidth = $(this).closest('a').css('width').replace('px', '');
        }
    });
}

Upvotes: 0

Views: 1254

Answers (3)

JF it
JF it

Reputation: 2403

as dragonslovetaco's has stated, you really should use CSS for this - check your updated fiddle:

http://jsfiddle.net/JCVnY/6/

Applying position:relative to the list items + having width:inherit on the a's will cause them to copy width.

a{background:red;display:inline-block; width:inherit;} li{position:relative; width:100%;}

Upvotes: 1

Felix
Felix

Reputation: 38102

You can do:

var $window = $(window);
$window.resize(function() {
    $('ul li').each(function () {
        var parentWidth = $(this).width();
        if ($(this).find('a').length) {
            $(this).find('a').width(parentWidth)
        }
    });
});

Updated Fiddle

Upvotes: 3

Damon
Damon

Reputation: 4484

If your anchor tags have a css property of "block" that should make the anchor element take the width of it's parent container. In this case, it is the "li" - which by default, is a block-level element.

If you are floating your list elements, give your "li" elements a width (using css). Then like you have now you can use "inline-block" to give your anchor tags a width (and/or height).

Upvotes: 1

Related Questions