1

As per the title really.

If notice that if I check $(elem).css('margin-top') it returns 0px even though I haven't explicitly set this style, either inline or in a stylesheet.

Basically I am setting the margin each time I hover over an element (to vertically align some content) so would rather just do this once.

I can't set the alignment on page load because the elements are hidden (display:none) so it needs to be done at the time they are displayed.

1
  • 1
    Actually the margin is set and working even when it is not displayed. jsfiddle.net/ZnbCn Commented Jun 15, 2011 at 16:48

3 Answers 3

4
if(!$(elem).data('hasSetMargin')){
    $(elem).css('margin-top', someValue);
    $(elem).data('hasSetMargin', true);
}
Sign up to request clarification or add additional context in comments.

Comments

2

What's the problem with setting it several times?

It looks like you're trying to early-optimize your code.

1 Comment

I wouldn't class this as early optimization. My requirements are to set it once. If there is a simple way of doing that rather than performing the margin calculation on every hover, then that is the option I would like to take.
1

It's not easy to tell because there are many sources which affect the value of a style such as margin-top.

However, you don't need to tell really because:

  1. Setting it more than once should do no harm in your case.
  2. You can improve your code by adding/removing/toggling HTML classes (addClass/removeClass/toggleClass) and styling the elements with pure static CSS (using class selectors) instead of setting the styles yourself. This has the added benefit of making your code readable.

Regarding the readability -- what would you rather read? This:

function() {
    $(selector).css('margin-top', '10px').css('border', '2px red solid');
}

or this:

function() {
    $(selector).addClass('update-pending');
}

1 Comment

unfortunately I can't use classes. The margin is calculated based on the contents of an element so it's not a question of just adding a css class. Whilst you say there is no harm setting the margin more than once, it still seems unnecessary. @Spycho's solution may be the solution to this.

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.