admin管理员组

文章数量:1330566

What is a smart way to name CSS classes to be able to distinct between those used for styling and those for JS events?

Looking at a div with 4 CSS classes, it would speed things up for me, if I could see if the class is used for only styling or only design, to reduce debugging-time.

I know I can start prefixing all CSS-style classes with style_, but is there a better way, that's maybe are a convention too?

What is a smart way to name CSS classes to be able to distinct between those used for styling and those for JS events?

Looking at a div with 4 CSS classes, it would speed things up for me, if I could see if the class is used for only styling or only design, to reduce debugging-time.

I know I can start prefixing all CSS-style classes with style_, but is there a better way, that's maybe are a convention too?

Share Improve this question edited Jun 29, 2017 at 11:23 radbyx asked Jun 29, 2017 at 11:10 radbyxradbyx 9,67022 gold badges90 silver badges133 bronze badges 5
  • So JavaScript specific and no jQuery? – Gezzasa Commented Jun 29, 2017 at 11:17
  • What I mean is you tagged javascript but not jQuery. I have a solution but jQuery only. – Gezzasa Commented Jun 29, 2017 at 11:20
  • I use jQuery too. I would love to hear your solution. – radbyx Commented Jun 29, 2017 at 11:23
  • Cool, Posted :) – Gezzasa Commented Jun 29, 2017 at 11:28
  • 2 There is a convention called BEM which is useful not only for JS/Style distinction but also for better naming practices. Check it here: getbem./naming hope it helps. – Amadeo Manouchehri Commented Jun 29, 2017 at 11:32
Add a ment  | 

2 Answers 2

Reset to default 8

Just use "js-" in the begining of all classes used for JS events.

With jQuery (don't know js solution) you can use data types and forget about selecting VIA class or ID.

https://jsfiddle/tcfhdfth/1/

<div data-event="changeBackground"><h1>hello</h1></div>

$("[data-event='changeBackground']").css('background-color', 'red');

You don't need to call it data-event. You can call it anything you like. Just not a reserved word.

To create listeners you can do the following.

$('body').on('click', "[data-event='changeBackground']", function () {
    $("[data-event='changeBackground']").css('background-color', 'red');
})

Performance is much better as explained here jQuery select by class VS select by attribute

本文标签: javascriptWhat is the naming convention for CSS classes for styling and for eventsStack Overflow