0

I am using a small JavaScript snippet to align the bottom edge with a small sidebar section ("Hot Right Now") with the bottom edge of the Featured Image section on a website I'm working on.

The script kicks in only once the entire p[age has loaded, and as a result, the section I'm trying to align jumps a bit. How should I modify the script to align it right away?

Here's the snippet I'm using:

<script type="text/javascript">
$( document ).ready(function() {
  var leftheight = $(".featured-image a img").offset().top + $(".featured-image a img").height();
  var rightheight = $('#top-posts-2').offset().top + $('#top-posts-2').height();
  var heightgap = leftheight - rightheight;
  $('#top-posts-2').css('padding-top', parseInt(heightgap + 3, 10) + 'px');
});
</script>
3
  • 2
    Do you know what $(document).ready(...) does? Commented Oct 17, 2013 at 19:48
  • Normal the ready() event trigger only when the document is loaded. Commented Oct 17, 2013 at 19:48
  • It did the same thing without $(document).ready(), actually... Commented Oct 17, 2013 at 19:49

1 Answer 1

2

Remove the $( document ).ready wrapper and put the script block immediately after the HTML element it is going to manipulate. You can't run it any earlier than this because the HTML you target needs to be in the page.

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

6 Comments

AND after the JQuery <script> tag
@Sebastien: even if jquery is loaded way before the body loading starts that is fine
that isn't true, you should place it above the HTML => encosia.com/dont-let-jquerys-document-ready-slow-you-down
@AkshayKhandelwal It depends on where you put the <script> tag of JQuery. If you put it in the <head> it will load before the body thus slowing the display of your page. If you put it in your body, the browser will load each tag by the order they are on the page this is why most people puts the JQuery <script> tag just before the closing tag of there body so the rendering of the page is'nt slowed down.
Thank you, @Diodeus – I tried your suggestion – the script doesn't seem to have any effect. Could you please take a look?
|

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.