Search code examples
jquerydynamicanchorcenter

Center container according to width of its anchor elements in Jquery


I need to center a container div which hosts a number of dynamic anchor tags. anchor tags vary sometimes I have 2 or just 1 and max I can have is 5 anchor tags.

I'm trying to get anchor tags's width by jquery to set width for the container.

but somehow anchor tag elements width is always returned as 0. I tried enclosing anchors in divs but still no result. I must say that anchors are floated left, but I've included a clear at the end just like always.

I have no problem centering element in jquery once I get its width, but I need to combine the width of all anchor tags to then center the outer container. .

Js fiddle here: In jsfiddle I've created two scenarios, one with fixed width when container is full so it can be centered css margin 0 auto. but when less anchor tags cannot get their width to recenter container


Solution

  • solved

    Js fiddle linked for solved solution

    problem was that while overwriting var storing widths it wasnt being done good.

    in each iteration it should have been :

    linksconitemswidth = parseFloat(linksconitemswidth) + ($(this).width());
    

    and important to cast string var to int with parseFloat() or parseInt()