Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting height of a DIV to correspond with location of anchor inside said DIV

Core issue : http://jsfiddle.net/pipip/P46Xg/
I have a div container with a few paragraphs of text,
and inside one of these paragraphs is the following anchor <a name="stop" />
The container is set to overflow:hidden

Is it possible with javascript / JQuery to set the height of the container so that the bottom of the container stops exactly at or below the anchor?

Added Depth & Background : http://jsfiddle.net/pipip/yj9dB/
This would be used for a modified JQuery Slider. Where someone using a CMS could type [readmore] anywhere into the Content field, which would be replaced by the above anchor via PHP. This way they would be easily able to control where the Read More break appears within the container. In the associated example I am hard-coding the height to 75px, although what I want is for the height to be dependent on the location of the anchor name="stop" in the text.

Thanks. If this is an awful way to go about it, I'm all ears!

like image 919
filip Avatar asked Nov 26 '11 01:11

filip


1 Answers

With jQuery you could do it like this:

$('#container').height( $('a[name=stop]').position()['top'] );

and CSS:

#container {
    position: relative;
}

We need this because .position() gives us the position relative to an element's offset parent, and we can make #container the offset parent of the anchor tag by setting its position to relative.

JSFiddle: http://jsfiddle.net/divad12/RYPm7/1/

Also, for HTML5, you may want to consider setting an anchor tag's id attribute instead of name: HTML Anchors with 'name' or 'id'?

like image 152
David Hu Avatar answered Oct 29 '22 20:10

David Hu