Add/Remove Class

We include our ‘core’ library, in the header


    <script src="../Include/Core.js" type="text/javascript"></script>
          

When this page loads, a click event is added to each of the four buttons. Clicking will add or remove classes (‘blue’ or ‘large’) from the paragraph of text in the middle of the page.

It does this using our ssAddClass and ssRemoveClass functions


      function preparePage()
      {
        ssAddEvent(document.getElementById("btnAddBlue"),"click",addBlue,false);
        ssAddEvent(document.getElementById("btnRemoveBlue"),"click",removeBlue,false);
        ssAddEvent(document.getElementById("btnAddLarge"),"click",addLarge,false);
        ssAddEvent(document.getElementById("btnRemoveLarge"),"click",removeLarge,false);
      }

      function addBlue()
      {
        ssAddClass(document.getElementById("para"),"blue");
      }

      function removeBlue()
      {
        ssRemoveClass(document.getElementById("para"),"blue");
      }

      function addLarge()
      {
        ssAddClass(document.getElementById("para"),"large");
      }

      function removeLarge()
      {
        ssRemoveClass(document.getElementById("para"),"large");
      }

      ssAddLoadEvent(preparePage);
          
in combination with the following style definitions

      .blue
      {
        background-color:#23a8bd;
        color:white;
      }

      .large
      {
        font-size:xx-large;
      }
          
  • It is quite elegant to change the appearance of elements in this way. An alternative approach would be to manipulate the individual style properties directly, like this...
    
        document.getElementById("para").style.backgroundColor="#23a8bd";
        document.getElementById("para").style.color="white";
                  
    but that is a lot more longwinded, especially when changing more than one property or removing style from a property,s or compounding changes on top of each other.