1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

hiding & unhiding a div with javascript

Discussion in 'HTML & Website Design' started by xXmahriXx, Oct 25, 2013.

  1. #1
    so I made a couple divs & I want to make it so that when I press on a link it shows only the div corresponding to it
    I tried
    <a href="#home" onclick="document.getElementById('home').display=inline">Home</a> 
    HTML:
    but I'm 140% that this is more than wrong

    heres the div its supposed to show
    <div id="playArea">
            <div id="home" style="display: none;">test</div>
            <div id="other1" style="display: none;">test</div>
            <div id="other2" style="display: none;">test</div>
            <div id="other3" style="display: none;">test</div>
            <div id="other4" style="display: none;">test</div>
        </div>
    HTML:
    what could I do ?
    I don't want to download any tabs script like tabbertab , I just want to make my own very simplistic one

    thanks
     
    Solved! View solution.
    xXmahriXx, Oct 25, 2013 IP
  2. XPEric

    XPEric Well-Known Member

    Messages:
    31
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    135
    #2
    Here's something that should help:

    Place this somewhere in the document-
    <script type="text/javascript">
        function toggle_visibility(id) {
          var e = document.getElementById(id);
          if(e.style.display == 'block')
              e.style.display = 'none';
          else
              e.style.display = 'block';
        }
    </script>
    Code (markup):
    And this is what you use to hide/unhide-
    <a href="#" onclick="toggle_visibility('item1');">Toggle visibility of item1</a>
    <div id="item1">Here's item1</div>
    Code (markup):
    Just know that you have to change "item1" in the second set to a custom value for it to work.
     
    XPEric, Oct 25, 2013 IP
  3. xXmahriXx

    xXmahriXx Member

    Messages:
    41
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #3
    wow thank you man :D
    as I have more divs & I wanted when I click a link only one appears & the others dissapear I modified it & it does what I want
    <html>
    <body>
    <script type="text/javascript">
        function toggle_visibility(id) {
          var e = document.getElementById(id);
          switch(e)
          {
            case item1:
                item2.style.display='none';
                item3.style.display='none';
                item4.style.display='none';
                break;
            case item2:
                item1.style.display='none';
                item3.style.display='none';
                item4.style.display='none';
                break;
            case item3:
                item1.style.display='none';
                item2.style.display='none';
                item4.style.display='none';
                break;
            case item4:
                item1.style.display='none';
                item2.style.display='none';
                item3.style.display='none';
                break;
          }
          e.style.display = 'block';
        }
    </script>
    <p onclick="toggle_visibility('item1');">Toggle visibility of item1</p>
    <p onclick="toggle_visibility('item2');">Toggle visibility of item2</p>
    <p onclick="toggle_visibility('item3');">Toggle visibility of item3</p>
    <p onclick="toggle_visibility('item4');">Toggle visibility of item4</p>
    <div id="item1">Here's item1</div>
    <div id="item2" style="display: none;">Here's item2</div>
    <div id="item3" style="display: none;">Here's item3</div>
    <div id="item4" style="display: none;">Here's item4</div>
    </body>
    </html>
    HTML:

    surprisingly my version works lol
    thank you again , I really have to learn more about js
     
    xXmahriXx, Oct 26, 2013 IP
  4. gorrillamcd

    gorrillamcd Member

    Messages:
    43
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    38
    #4
    Hey @xXmahriXx,

    That's great that you figured out a solution. Your solution will work, but what if you need to add a 5th div? You then also have to modify your javascript. I'm not a javascript guru, but I did a bit of googling and found what I think is a more robust solution:

    var previousVisibleElement;
    function toggle_visibility(id,$this) {
      var e = document.getElementById(id);
      if(e.style.display == 'block')
      {
        e.style.display = 'none';
      }
      else
      {
        if(previousVisibleElement !=null)
              previousVisibleElement.style.display='none';
        e.style.display = 'block';
        previousVisibleElement=e;
    
      }
    }
    Code (markup):
    It uses the same technique as above, but stores the visible div's id in a global variable. It then hides that div while showing the newly clicked one. This should work for any number of div's. Here's the reference: http://stackoverflow.com/questions/...lity-of-divs-using-javascript/7743894#7743894
     
    gorrillamcd, Oct 26, 2013 IP
  5. #5
    While the above works after a fashion, I'd take a bit different a tack on this. First up I'd keep the extra wrapping DIV as something to target automatically, so the script can figure out how many sub-div are children of it, and auto-generate the right number of tab controls. The text for the tabs could then be passed in those DIV's TITLE attribute thus:
    <div id="testTabs">
    	<div title="tab 1">Test Content 1</div>
    	<div title="tab 2">Test Content 2</div>
    	<div title="tab 3">Test Content 3</div>
    	<div title="tab 4">Test Content 4</div>
    	<div title="Simple, no?">Test Content 5</div>
    </div>
    Code (markup):
    That way our tabify function can just be passed the ID of the outermost container.
    tabify('testTabs');
    Code (markup):
    Instead of using display state, I'd do a class swap and set the display in the CSS. This opens the door to other effects like dissolves or slides using CSS3 if the elements are the same size, with a minimum of muss and fuss.

    To build the tab controls (which is pretty much what you're asking for) I'd insertBefore a UL in the target wrapping DIV, and add LI to it with the title inside it using the DOM. DOM construction doesn't force a reparse (unlike InnerHTML) making it faster, even if it does feel like a bit more code. I'd also make the onclick event for those controls also do a class swap, so that too can be styled... tracking the old ones I'd do what @gorrillamcd suggested and track the previous element rather than try and go through all the existing ones to unset them.

    For proper graceful degradation I'd set a class on that outer DIV when scripting works as the trigger/target for all script related CSS. Combined with adding the scripting only controls from the script, this gives a nice graceful degradation of all your little subsections showing when scripting is disabled/unavailable, as well as not showing any controls that wouldn't do anything.

    ... and to handle the class swap I'd throw in a few simple functions rather than diving for some fat bloated library.

    Class functions:
    function classExists(e, n) {
    	return new RegExp('(\\s|^)' + n + '(\\s|$)').test(e.className);
    }
    
    function classAdd(e, n) {
    	if (!classExists(e, n)) {
    		e.className += (e.className ? ' ' : '' ) + n;
    	}
    }
    
    function classRemove(e, n) {
    	e.className = e.className.replace(
    		new RegExp('(\\s|^)' + n + '(\\s|$)'),' '
    	) . replace(/^\s+|\s+$/g,'');
    }
    Code (markup):
    Tabify function:
    function tabify(targetId) {
    
    	var
    		d = document, t, e,
    		current = false, currentTab = false,
    		parent = d.getElementById(targetId),
    		tabs = d.createElement('ul'),
    		divList = [];
    		
    	if (e = parent.firstChild) {
    	
    		do {
    			if (e.tagName == 'DIV') divList.push(e);
    		} while (e = e.nextSibling);
    		
    		if (divList.length > 0) {
    		
    			function setCurrent(t) {
    				if (current) classRemove(current, 'current');
    				if (currentTab) classRemove(currentTab, 'current');
    				classAdd(current = t.tabTarget, 'current');
    				classAdd(currentTab = t, 'current');
    			}
    			
    			for (t = 0; t < divList.length; t++) {
    				classAdd(divList[t],'tabDiv');
    				e = d.createElement('li');
    				e.appendChild(d.createTextNode(divList[t].title));
    				e.tabTarget = divList[t];
    				e.onclick = function(e) {
    					e = e || window.event;
    					setCurrent(e.target || e.srcElement);
    				};
    				tabs.appendChild(e);
    			}
    			
    			classAdd(parent,'scriptedTabs');
    			classAdd(tabs,'tabList');
    			parent.insertBefore(tabs, parent.firstChild);
    			setCurrent(tabs.firstChild);
    			
    		}
    		
    	}
    	
    }
    Code (markup):
    I add 'tabDiv' in the scripting to the direct children DIV of our wrapper so as to avoid using child selectors, which don't work in older versions of IE. If you don't care about those, that classAdd line could be axed and the CSS changed as appropriate. Honestly, I'd keep it as it's not a significant amount of code and makes it work all the way back to IE 5.5

    I put up a live demo here with some extra CSS to make it pretty:
    http://www.cutcodedown.com/for_others/xXmahriXx/template.html

    As with all my examples the directory:
    http://www.cutcodedown.com/for_others/xXmahriXx/

    ... is wide open for easy access to the gooey bits and pieces. Feel free to have a look around.

    So scripting off graceful degradation, CSS off graceful degradation, minimalist markup by not putting scripting only content in the markup, and automatically lets you add or remove tabs/subcontent with ease.

    Hope this helps, any questions fire away.
     
    deathshadow, Oct 26, 2013 IP
    gorrillamcd and ryan_uk like this.
  6. gorrillamcd

    gorrillamcd Member

    Messages:
    43
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    38
    #6
    Thanks @deathshadow. That's a much better solution than either of the above. It's much better to separate the scripting from the markup like you've shown.
     
    gorrillamcd, Oct 27, 2013 IP
  7. xXmahriXx

    xXmahriXx Member

    Messages:
    41
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #7
    wow thanks guys
    that looks so much simpler but as my css & javascript knowledge isn't that good I'll stick around with my version until I can fully understand yours
    again thank you
     
    xXmahriXx, Oct 27, 2013 IP