Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I avoid using jQuery selectors on CSS classes that are defined in style sheets?

Tags:

html

jquery

css

I am concerned with using CSS classes that are defined in style sheets with my jQuery selectors. The reason for this is when a CSS class is defined in a style sheet there are many reasons for a developer/designer to change the name of the class or how it is used in the html that is detached from the jQuery selector that also uses the class. There is nothing obvious that tells the developer/designer that they need to account for JavaScript functionality when making this change.

Would it be better to just avoid coupling jQuery selectors with legit CSS classes, but instead use CSS classes that are not tied to any styles and have a say a prefix like 'j_' that makes it's purpose obvious that is to be used exclusively as a jQuery selector? This would make the coupling less fragile at the cost of an extra class name in the markup. This would also make validation engines that find undefined classes less useful but the prefix would hopefully make it obvious that those classes serve a purpose as jQuery selectors.

....

I understand that CSS classes should be named based on their functionality. I do not however believe that naming the class that way solves the problem. Developers/Designers will still change the name even though their new name is still describing the same functionality, or they may modify where it is used. In these cases it is not obvious that these changes will impact the JavaScript functionality.

like image 580
Blegger Avatar asked Mar 04 '09 22:03

Blegger


1 Answers

The css class name should describe the function of the element, not the style that it applies to it. If you have a sidebar that is floated to the left, call the class sidebar, not leftFloat. This way you can put the style of the sidebar in the sidebar class in css and apply whatever jquery functions you need.

Edited to clarify one of the comments: You shouldn't have to rename the classes or id's of the elements. If you have a sidebar, then maybe it changes to be a toolbar instead, or a top navigation. Does it matter that it is still called a sidebar? The user never notices. Or you could give everything really abstract names, like navigation-pane and main-content.

I started a webapp with jQuery for internal use last week, and I've changing the name of only one id, because I needed to generalize it more. Apart from that every class and id kept exactly the same name.

like image 105
Marius Avatar answered Oct 24 '22 10:10

Marius