2

I have a simple text inside span. I just wanted to animate it from right to center of the #maincontainer. Therefore i did a calculation to make it center horizontally. I tried with outerWidth() as well. It didn't work. Here is the code.

<span id="headline">Hi There! Say hello to world.</span>

#maincontainer width is 728m But #headline container is giving wrong calculation every time.

$("#headline").css({"top": (($("#maincontainer").height()-($("#headline").height()))/2)}).delay(1e3).animate({
    "right":  $("#maincontainer").width() - $("#headline").width() + "px"
},5e2); 
2
  • 1
    any fiddle available?? Commented Dec 22, 2015 at 7:54
  • may be simpler with CSS. Commented Dec 22, 2015 at 7:55

2 Answers 2

3

1/ <span> as an inline element, has no dimensions. Asking for them will return "undefined".

Tranform <span> to an inline-block element with CSS.

<span style="display:inline-block" id="headline">

Why inline-block and not block ? Because you want the width of the displayed text only, and not the width of a whole block (same as the container probably).

2/ Also, width() or style.width will give a blank result if width has not been previously defined for the element.

In this case, use: $("#headline").offsetWidth

Sign up to request clarification or add additional context in comments.

Comments

0

width() and height() methods don't work on html elements who has display:inline style.span by default is with display:inline. to fetch width or height you can use display:block or display:inline-block.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.