Question

Being a front-end developer working in a team, I have found myself solving a recurring problem many times. For example, much of our frontend javascript code is written using jQuery and CSS selectors (mostly targeting a CSS "class"). The problem is, is that many times another developer that is fixing some CSS code will remove a class or will change the DOM element nesting it under another element making the JS code break.

To prevent this, my idea was to use/add a "data-js" attribute to each element that we want to use for Javascript. However I am not sure about the performance of a jQuery selector written like this:

$('[data-js="my_js_selector"]').click();

Another idea I had, was to add a js-specific class to a dom element that is somehow manipulated by Javascript:

<a href="lol.com" class="js-link">link</a>

and then calling it simply with $('.js-link').click()

It would be very nice that you could only look into HTML and tell that some element has some Javascript manipulations attached without actually looking into the JS code.

Is this a good idea? Or are there some other best practices to separate JS-triggering from CSS styling?

Était-ce utile?

La solution

In Scalable and Modular Architecture for CSS (SMACSS), Jonathan Snook teaches that a "state" class such as the one you proposed with .js-link is the best approach.

The relevant discussion is in the section on State Rules:

Sub-module styles are applied to an element at render time and then are never changed again. State styles, however, are applied to elements to indicate a change in state while the page is still running on the client machine.

For example, clicking on a tab will activate that tab. Therefore, an is-active or is-tab-active class is appropriate. Clicking on a dialog close button will hide the dialog. Therefore, an is-hidden class is appropriate.

This contradicts what two commenters said. CSS code and classes should be flexible; CSS developers should be able to refactor and improve code without worrying about breaking functionality not related to presentation.

The point made by @ArunPJohny supports the state class approach. Engines are unfortunately not optimized to recognize data- attributes any more than they are to recognize arbitrary custom attributes, such as foo-.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top