Lee
Lee

Reputation: 4323

Is there a more efficient way to run this on page load and resize?

I'm using this to dynamically adjust the body top margin when the window is resized, for responsiveness.

$(window).resize(function() {
    $('body').css('margin-top', $('#header').height());
});

But I'm trying to find a more efficient way to run the same line on page load, without just coping the line again like:

$('body').css('margin-top', $('#header').height());
$(window).resize(function() {
    $('body').css('margin-top', $('#header').height());
});

Upvotes: 0

Views: 48

Answers (1)

Alex
Alex

Reputation: 10226

Performance-wise, it is best practice to run the code inside resizing events within a timeout. Also, it is a good idea to save the elements in a variable.

Last but not least, use namespaces for your events to trigger them explicitly.

var winresizeT,
    $body = $('body'),
    $window = $(window),
    $header = $('#header');

$window.on('resize.bodymargin', function() {
  clearTimeout(winresizeT);
  winresizeT = setTimeout(function() {
    $body.css('margin-top', $header.height() + 'px');
  }, 30);
});

$window.on('load', function() {
  $window.trigger('resize.bodymargin');
});

Upvotes: 1

Related Questions