Wednesday, December 12, 2012

Day and Night Effect Using jQuery

Day and night effect on any html page can easily mean switching between two different stylesheets to enhance user experience. This tutorial will demonstrate how to switch between two stylesheets efficiently using jQuery.

End Result:



THINGS YOU MIGHT NEED:
jQuery basic knowledge
HTML file 
External CSS files

External "day.css" file:
body {
     
      color: black;
      background-color: yellow;  } 
External "night.css" file:
body {
     
      color: white;
      background-color: black; }

HTML file:
<body>
  <h1>Day and Night Effect</h2>

   <button data-file="day"> Day </button>
   <button data-file="night"> Night </button>
</body>
jQuery Script:
<script>
 
  (function () {
   
    var link = $('link');
    $('button').on('click', function() {
        
            var $this = $(this),
            stylesheet = $this.data('file');

            link.attr('href', stylesheet + '.css');

            $this
                .siblings('button')
                  .removeAttr('disabled')
                  .end()
                  .attr('disabled', 'disabled');      

          });

     })();

</script>
Code Dive:

CSS:
External "day.css" and "night.css" can hold your custom CSS styles respectively.

jQuery:
We first start by calling a self involking anonymous function that listens to button clicks and executes immediately. That is:
(function () {

}) ();

The rest of the code are commented to customize your own methods.

var link = $('link'); // dives into html retrieve and assign css 'link' attribute
    $('button').on('click', function() { // on mouse click even. reference jQuery d                                         //docs for other event helpers.
            var $this = $(this),
            stylesheet = $this.data('file'); // retrieve button data file attr 

            link.attr('href', stylesheet + '.css'); // alter the attr respectively

            $this                         // get the button that was clicked
                .siblings('button')       // change selection to a sibling button
                  .removeAttr('disabled') // remove its attributes 
                  .end()                  // end or return
                  .attr('disabled', 'disabled');  // and disable the button itself.

Happy Coding!
verse316

No comments:

Post a Comment