0

Current Design

In a website I am designing I have a number of elements that initially will appear hidden, until the user needs to see them. For example they have scrolled to a desired height on the page.

Currently this works by JavaScript adding a class line.classList.add('show-header-line');

Which in CSS will be defined next to the main styling for the element. This show variant of the class will only contain attributes required to make the element visible opacity: 1. The main styling for the element will contain the opposite attributes required to hide the element initially opacity: 0.

The Alternative

Of course this could work the other way around. With a class designed to hide the element initially being set in the html, then to be removed when required by JavaScript.

HTML

<div class="header-line hide-header-line" />

JS

line.classList.remove('hide-header-line');

Note

Of course I could add and remove styles directly (without the need for extra classes) in the JavaScript, but this seems much worse. Regarding a lack of separation of concerns.

Question

My current approach means the resulting rendered DOM is littered with elements that have main style class and a show class. The alternative means my html file is littered with elements with a main style class and a hide class. Which is considered better practice? Is there another cleaner way I could be doing this?

Community
  • 1
  • 1
Michael Hancock
  • 2,673
  • 1
  • 18
  • 37
  • 2
    From what side do you start to eat a banana? I think it is just a matter of taste. I prefer to hide elements I don't want to show and then add `.open` class to them. You should think of something like what if user will have javascript disabled, do you want the items to be visible or hidden... – JSEvgeny Sep 29 '17 at 10:59
  • @JavaEvgen You make a good point. With JavaScript disabled the site becomes pretty difficult to use. Right now I am just planning to a ` – Michael Hancock Sep 29 '17 at 13:00

1 Answers1

1

I would strongly suggest against using opacity:0 for this, rather use display: none. The reason being that an element with opacity: 0 still occupies space in the markup, whereas display: none will add the element to the DOM, but it won't be rendered in the markup (if that makes sense).

Here is a more detailed explanation

Also, an example using the scroll pass certain point you said, this is how I would do it, note code is untested.

window.addEventListener('scroll', function(){
  document.querySelector('#navigation').classList[this.scrollTop > 200 ? 'add' : 'remove']('fixed-nav');
});

css

.fixed-nav {
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
}
Baruch
  • 2,381
  • 1
  • 17
  • 29