Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way keep track of your identifiers for your Jquery and CSS?

This is more of an organisation question concerning Jquery.

Using the following simple example:

<a href="#" class="click">click me</a>

<script>
$(document).ready(function(){
    $('.click').on('click',function(){
          alert('Clicked!');
    });
});
</script>

Now multiply this by a 1000 on your website, it can quickly get messy. You also can forget which classes you attributed for Jquery or for your CSS. I usually try to avoid mixing both, so I add my classes for CSS and others for the Jquery, in case I change I the layout or use that section somewhere else, ... I can change the CSS. But how to do you remember which one is for CSS or Jquery? Do you name your classes "JSclassName" or something like that?

Let me know if I'm not clear and thanks for your help.

like image 623
denislexic Avatar asked Aug 09 '12 06:08

denislexic


1 Answers

  • Have a consistent naming scheme for your "sections" in terms of case and meaning
  • Keep id and class names the same both for CSS and JS to avoid the confusion.
  • Relating to semantic code, you should give meaning to the class/id names as well. This helps you remember what you are adding code for. Don't use something like "centeredContainer" or "thisIsClickable".

Example:

<section class="weatherWidget">
    <ul class="forecast">
        <li class="vicinity">
           ...
    <ul class="news">
        <li class="region">
           ...

I also namespace my CSS and JS to avoid conflicts. The following code ensures that only weather widget contents are referenced by the code:

//this click event is only for weatherWidget vicinity
$('.weatherWidget .vicinity').on('click',function{...});

//this CSS is only for weatherWidget regions
.weatherWidget .region{...}

Also, although I don't really use them nor endorse using them, LESS and SASS frameworks can also help in terms of avoiding redundant CSS code by using variables.

like image 197
Joseph Avatar answered Sep 28 '22 15:09

Joseph