Share it

Bookmark and Share

Translate

Tuesday, May 17, 2011

1 Multiple $(document).ready():Hide and Show elements in a page

One more great thing about $(document).ready() that I didn't mention in my previous post is that you can use it more than once. In fact, if you don't care at all about keeping your code small, you could litter your javascript file with them. It's great to be able to group your functions within a file or even across multiple files, and jQuery's flexible $(document).ready() function allows you to do that, pain free. You could, for example, have one .js file that is loaded on every page, and another one that is loaded only on the homepage, both of which would call $(document).ready(). So, inside the <head> tag of your homepage, you would have three references to JavaScript files altogether, like so:
HTML:
  1. <script src="/js/jquery.js" type="text/javascript"></script>
  2. <script src="/js/common.js" type="text/javascript"></script>
  3. <script src="/js/homepage.js" type="text/javascript"></script>

You could also do something like this inside a single .js file:
JavaScript:
  1. $(document).ready(function() {
  2.   // some code here
  3. });
  4. $(document).ready(function() {
  5.   // other code here
  6. });

A final note: In a comment to my previous post, Jörn gave this excellent tip for shrinking your code: Even for this little amount of code is a shortcut available:
$(function() {
// do something on document ready
});
A function passed as an argument to the jQuery constructor is bound to the document ready event.
Code:
Java script

    <script src="/js/jquery.js" type="text/javascript"></script>
    <script>
    $(document).ready(function() {
     // hides the slickbox as soon as the DOM is ready
   
      $('#slickbox').hide();
      $('#slickbox2').hide();
      $('#slickbox3').hide();
     // shows the slickbox on clicking the noted link 
      $('#slick-show').click(function() {
        $('#slickbox').show();
        $('#slickbox2').hide();
      $('#slickbox3').hide();
        return false;
      });
     // hides the slickbox on clicking the noted link 
      $('#slick-hide').click(function() {
         $('#slickbox').hide();
         $('#slickbox3').hide();
        $('#slickbox2').show();
       
        return false;
      });
    
     // toggles the slickbox on clicking the noted link 
        $('#slick-toggle').click(function() {
        $('#slickbox').hide();
        $('#slickbox2').hide();
        $('#slickbox3').show();
        return false;
      });
    });
</script>

HTML
<div id="slickbox">test1</div>
<div id="slickbox2">test2</div>
<div id="slickbox3">test3</div> 

<a href="#" id="slick-show">Show</a>
<a href="#" id="slick-hide">show2</a>
<a href="#" id="slick-toggle">toggle</a>


1 comments:

Thanks for your valuable Comment

 

TechnoTipworld- Tips,Tricks,Technology Copyright © 2011 - |- Template created by O Pregador - |- Powered by Blogger Templates