How to set top position using jquery

Jquery

Jquery Problem Overview


I am creating custom div scroller and want to set top position of content div. My jquery code is as below:

containerOuterHeight=$("#messagePopUpContainer").outerHeight();
			contentOuterHeight=$("#content").outerHeight();
			contentTopPosition=$("#content").offset().top;
			alert("contentTopPosition"+contentTopPosition);
			alert(contentTopPosition-(containerOuterHeight/20));
			$("#content").offset().top=contentTopPosition-(containerOuterHeight/20);
			//$("#content").css("top",( contentTopPosition-(containerOuterHeight/20) ) + "px");
			alert("contentTopPosition"+$("#content").offset().top);
			//alert("Fontsize"+$('#content').css('font-size') );

and html is:

<div id='messagePopUpContainer' style='background-color:#ffffff; overflow: hidden;'>
<a href='javascript:void(0);' id='popupanchor' onkeydown='PopupKeyHandler("' + elmId + '");'></a>

<div id='content' style='width:350px'>' + methods.settings[elmId].text + '</div >
<div id='popupReturn'>Return</div></div></div>'

Jquery Solutions


Solution 1 - Jquery

You can use CSS to do the trick:

$("#yourElement").css({ top: '100px' });

Solution 2 - Jquery

Accessing CSS property & manipulating is quite easy using .css(). For example, to change single property:

$("selector").css('top', '50px');

Solution 3 - Jquery

You could also do

   var x = $('#element').height();   // or any changing value

   $('selector').css({'top' : x + 'px'});

OR

You can use directly

$('#element').css( "height" )

The difference between .css( "height" ) and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation. jquery doc

Solution 4 - Jquery

Just for reference, if you are using:

 $(el).offset().top 

To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:

$(el).offset({top: pos});

As opposed to the CSS methods above.

Solution 5 - Jquery

And with Prototype:

$('yourDivId').setStyle({top: '100px', left:'80px'});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajanikant ShuklaView Question on Stackoverflow
Solution 1 - JqueryRavi GadagView Answer on Stackoverflow
Solution 2 - JqueryStarxView Answer on Stackoverflow
Solution 3 - JqueryCG_DEVView Answer on Stackoverflow
Solution 4 - JqueryCameronView Answer on Stackoverflow
Solution 5 - JqueryehrhardtView Answer on Stackoverflow