Hide/Show and Toggle DIV usng JavaScript

Discussion in 'JavaScript and AJAX' started by Shree Limbkar, Feb 6, 2009.

  1. Shree Limbkar

    Shree Limbkar New Member

    Joined:
    May 29, 2008
    Messages:
    6
    Likes Received:
    1
    Trophy Points:
    0
    Location:
    Pune
    Code:
    //  The functions have been adapted from various sources
    //  and re-written to provide maximum flexibility
    //  and compatability with various browsers.
    
    //Global Declarations
    var ie = (document.all) ? true : false;
    
    function toggleClass(objClass){
    //  This function will toggle obj visibility of an Element
    //  based on Element's Class
    //  Works with IE and Mozilla based browsers
    
      if (getElementByClass(objClass).style.display=="none"){
        showClass(objClass)
      }else{
        hideClass(objClass)
      }
    }
    
    function hideClass(objClass){
    //  This function will hide Elements by object Class
    //  Works with IE and Mozilla based browsers
    
    var elements = (ie) ? document.all : document.getElementsByTagName('*');
      for (i=0; i<elements.length; i++){
        if (elements[i].className==objClass){
          elements[i].style.display="none"
        }
      }
    }
    
    function showClass(objClass){
    //  This function will show Elements by object Class
    //  Works with IE and Mozilla based browsers
    var elements = (ie) ? document.all : document.getElementsByTagName('*');
      for (i=0; i<elements.length; i++){
        if (elements[i].className==objClass){
          elements[i].style.display="block"
        }
      }
    }
    
    function toggleID(objID){
    //  This function will toggle obj visibility of an Element
    //  based on Element's ID
    //  Works with IE and Mozilla based browsers
    var element = (ie) ? document.all(objID) : document.getElementById(objID);
      if (element.style.display=="none"){
        showID(objID)
      }else{
        hideID(objID)
      }
    }
    
    function hideID(objID){
    //  This function will hide Elements by object ID
    //  Works with IE and Mozilla based browsers
    var element = (ie) ? document.all(objID) : document.getElementById(objID);
      element.style.display="none"
    }
    
    function showID(objID){
    //  This function will show Elements by object ID
    //  Works with IE and Mozilla based browsers
    var element = (ie) ? document.all(objID) : document.getElementById(objID);
      element.style.display="block"
    }
    
    function getElementByClass(objClass){
    //  This function is similar to 'getElementByID' since there
    //  is no inherent function to get an element by it's class
    //  Works with IE and Mozilla based browsers
    var elements = (ie) ? document.all : document.getElementsByTagName('*');
      for (i=0; i<elements.length; i++){
        //alert(elements[i].className)
        //alert(objClass)
        if (elements[i].className==objClass){
        return elements[i]
        }
      }
    }
     
    Last edited by a moderator: Feb 6, 2009
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  4. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Using jQuery its a piece of cake.

    Code:
    $('#idOfMyDiv').hide(); // hides the div with id 'idOfMyDiv'
    $('.myClassName').hide(); //hides all elements having the classname 'myClassName'
    
    Similarly, the show function will unhide the element(s). Enjoy
     
  5. bluantinoo

    bluantinoo New Member

    Joined:
    Jun 4, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi everybody,
    I was looking exactly this thing: how to toggle all elements in a page having a certain class.

    I have used this method, but I get this js error:

    getElementByClass(objClass) is undefined

    does anybody imagine why?
     
  6. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
  7. gkumar

    gkumar New Member

    Joined:
    Jun 16, 2009
    Messages:
    58
    Likes Received:
    5
    Trophy Points:
    0
    Hide and Show a Div Using Javascript:-This tutorial will show you how to create a hidden Div and display it with the click of a link. There are a few reasons you may want to hide a Div in a website design. You may want to create a drop down type menu or a box that will show more information when you click a link. Another reason would be for SEO purposes. In theory hiding information in a Div is not against Google’s rules. As long as the user can still see the content when clicking a button you are not displaying different information to the user than you are to the search engine.

    First we are going to start with a very basic page layout and create a 2 Divs. One will be shown and one will be hidden. Here is the starting code.
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Hidden Div</title>
    </head>
     
    <body>
    <div id="main">This is not hidden.</div>
     
    <div id="hidden">This is hidden.</div>
     
    </body>
    </html>
     
    Ok now I will add some basic style to these boxes.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Hidden Div</title>
     
    <style type="text/css">
    <!--
    #main{
    width:500px;
    height: 20px;
    background: lightblue;
    }
    #hidden {
        width:300px;
        height:20px;
        background: lightgrey;
    }
    -->
    </style>
     
    </head>
     
    <body>
    <div id="main">This is not hidden.</div>
     
    <div id="hidden">This is hidden.</div>
     
    </body>
    </html><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Hidden Div</title>
    </head>
     
    <body>
    <div id="main">This is not hidden.</div>
     
    <div id="hidden">This is hidden.</div>
     
    </body>
    </html>
     
    Ok now I will add some basic style to these boxes.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Hidden Div</title>
     
    <style type="text/css">
    <!--
    #main{
    width:500px;
    height: 20px;
    background: lightblue;
    }
    #hidden {
        width:300px;
        height:20px;
        background: lightgrey;
    }
    -->
    </style>
     
    </head>
     
    <body>
    <div id="main">This is not hidden.</div>
     
    <div id="hidden">This is hidden.</div>
     
    </body>
    </html>
    Seven ways to toggle an element with JavaScript:-There are litterally an unlimitted number of ways to toggle an element’s display with JavaScript. Some, more useful than others. Dating back to the late nineties, toggling is perhaps the oldest trick in the book within JavaScript development. However, to this day, it still proves itself useful as hiding/showing elements can improve user interaction (when done tastefully).

    Anyway, here are seven ways toward achieving just that.
    The bottom line
    First off, this is perhaps the simplest and shortest way to toggle.
    toggling the short way

    Code:
    // showing
    document.getElementById('element').style.display = '';
    // hiding
    document.getElementById('element').style.display = 'none';
    
    So let’s make this into a function that’ll get the job done real quick like:
    show? or hide?

    Code:
    function toggle(obj) {
    	var el = document.getElementById(obj);
    	if ( el.style.display != 'none' ) {
    		el.style.display = 'none';
    	}
    	else {
    		el.style.display = '';
    	}
    }
    
    Well that was easy. But we can also go ternary style.
    toggling ternary style
    Code:
    function toggle(obj) {
    	var el = document.getElementById(obj);
    	el.style.display = (el.style.display != 'none' ? 'none' : '' );
    }
    
    Cool. Hey, ever heard of the dollar function? If that’s sittin’ around somewhere, let’s use it!
    toggling with the ternary dollar
    Code:
    // our dollar function
    function $() {
    	var elements = new Array();
    	for (var i = 0; i < arguments.length; i++) {
    		var element = arguments[i];
    		if (typeof element == 'string')
    			element = document.getElementById(element);
    		if (arguments.length == 1)
    			return element;
    		elements.push(element);
    	}
    	return elements;
    }
    // and now our improved toggler!
    function toggle(obj) {
    	var el = $(obj);
    	el.style.display = (el.style.display != 'none' ? 'none' : '' );
    }
    
    Cool. Now that we’ve got this thing nice and compact… can’t we do anything else to make it cool? Why, of course. Let’s say, instead of limitting it to just one object, let’s say “unlimitted.”
    toggling multiple objects
    Code:
    function toggle() {
    	for ( var i=0; i < arguments.length; i++ ) {
    		$(arguments[i]).style.display = ($(arguments[i]).style.display != 'none' ? 'none' : '' );
    	}
    }
    
    Sweet. Now that looks nice and sexy (quite personally, I think it’s the sexi’est’). But let’s see if we can extract any of these into “showing” versus “hiding” using an object literal.
    separating showing and hiding
    Code:
    var toggle = {
    	show : function(obj) {
    		document.getElementById(obj).style.display = '';
    	},
    	hide : function(obj) {
    		document.getElementById(obj).style.display = 'none';
    	}
    };
    
    Alright alright alright, I can dig that. But what happened to using our dollar buddy? Surely we can get that back in the mix.
    separating showing and hiding
    Code:
    var toggle = {
    	show : function(obj) {
    		$(obj).style.display = '';
    	},
    	hide : function(obj) {
    		$(obj).style.display = 'none';
    	}
    };
    
    Ok, why not even give it the flexibility of passing in as many arguments as we want to either? Ok, no problem.
    separating showing and hiding
    Code:
    var toggle = {
    	show : function() {
    		for ( i=0; i < arguments.length; i++ ) {
    			$(arguments[i]).style.display = '';
    		}
    	},
    	hide : function() {
    		for ( i=0; i < arguments.length; i++ ) {
    			$(arguments[i]).style.display = 'none';
    		}
    	}
    };
     
  8. naimish

    naimish New Member

    Joined:
    Jun 29, 2009
    Messages:
    1,043
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Engineer
    Location:
    On Earth
    Are this all old articles ? I mean before May-June ?
     
  9. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  10. David Michael

    David Michael New Member

    Joined:
    Jul 6, 2009
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    awesome!this is the best article for me!It would be easy if they show it in xhtml and in a css sheet.
     
  11. kien_vn

    kien_vn New Member

    Joined:
    Aug 31, 2010
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    I usually use this function, it work fine

    Code:
    var ie = (document.all) ? true : false;
    function toggleObj(obj) {
      
         try{
            var el;
            try{
            
                el = (ie) ? document.all(obj) : document.getElementById(obj);
            }
           catch(err)
           {
                el= document.getElementById(sm);
           }
    
            if ( el.style.display != 'none' ) {
                el.style.display = 'none';
                
            }
            else {
                el.style.display = 'block';
                
            }
        }catch(err)
        {
        
        }
    }
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice