Jump to content
Johann

Hide and show elemets

Recommended Posts

Dear W3-school supporter and friends,

 

is there a simple way to make certain elements (id) hidden on demand (on click)?

 

I have content pages with "a lot" of info in the upper part and in the foot part and it would be nice is the reader could press am element and those parts would be hidden so that he/she could concentrate on reading just the content.

 

And some footing parts (terms of use details) would be great to have vici versa. That means the details would be just show on demant for certain elements (id's)

 

Is there a way without using and special apps, or third part functions?

 

Thanks a lot for hints!

Share this post


Link to post
Share on other sites

Not with css ( well you can using :target and anchor bookmark link where you link to id ref using href="#idref", but! after hiding target id ref content you can't reverse it to show again or vice versa), with events such as 'onclick the best option would be to use Jquery/JavaScript. look up 'accordion' in jquey its quit easy to setup.

Share this post


Link to post
Share on other sites

Thanks a lot for you hints, dsonesuk!

.

Yes I have seen and tested some iquerys, nice play stuff, but I am not so happy with googleapps and similar third part companies.

 

I have tried a little with

 

function off(){document.getElementById("F_sourceTitle").style.display="none";}

 

So to hide some seems to be "easy" (not sure how to get more then one certain id yet) but I have not found a way to:

 

* redisplay previous hidden elements

* hide certain elements at the first place and make them only visible on demand (no java user should get them visible any way as it is about terms of use.

 

I hope I am not to bothersome with my many questions without much knowledge.

Share this post


Link to post
Share on other sites

It is not clear to me whether you want to hide individual text fields or entire areas of the page. For text fields you could try something that Hadien just mentioned in another message thread, like...

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>show/hide</title><style>article{width:600px;border:1px dotted black;}.showmore{max-height: 100px;overflow:hidden;/* hide excessive text */}.showall{overflow: auto;}</style><script>function showHide(link){var article = link.previousSibling;while(article.nodeName!='ARTICLE'){// find the previous articlearticle = article.previousSibling;}if(article.className=='showall'){link.innerHTML = '[Show More]';article.className='showmore';}else{link.innerHTML = '[Hide]';article.className='showall';}}</script></head><body><article class="showmore"><p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p></article><a href="#" onclick="showHide(this);">[Show More]</a></body></html>
Edited by davej

Share this post


Link to post
Share on other sites

Thanks a lot davej!

 

That looks very great and I need to study and experiment a little with it, to understand it better.I have a lot of <div> with specific id's which and it's that try to find a way to change as less as possible within the html files (many pages).

 

Generally that seems to go in the right direction. Two things I face with no quick idea. Is it possible to make it for ids? And is it possible to call more than one ID for this action.The cut by size (height) is not so important, as it would show and hidde a whole div (of a certain id)

 

(As I had seen, that is no more css or html. I apologies the further use of this topic here and hope that is ok for the forum team here. If not, I would like to request to maybe move it to the ? java section ... not sure)Thanks

Edited by Johann

Share this post


Link to post
Share on other sites

Dear davej,

Dear dsonesuk,

 

I guess I could manage something useful with davejs code. Just build the article around this space.How ever, in case of the hiding of Divisions on ids, I still have trouble. As the sites are not all equal and have different division ids included, it always strikes if one of the id is actually missing. Is there a way around?I used to use it in this way:

<script>function off(){document.getElementById("H_homage").style.display="none";document.getElementById("F_footer").style.display="none";document.getElementById("H_search").style.display="none";document.getElementById("H_crumbtrail").style.display="none";document.getElementById("H_copyright").style.display="none";document.getElementById("F_read").style.display="none";document.getElementById("H_docBy").style.display="none";document.getElementById("H_docAuthor").style.display="none";document.getElementById("H_tipitakaLinks").style.display="none";document.getElementById("H_tipitakaID").style.display="none";document.getElementById("H_docAuthorTrans").style.display="none";document.getElementById("H_docAuthorTransInfo").style.display="none";document.getElementById("H_docAuthorTransAlt").style.display="none";document.getElementById("H_altFormat").style.display="none";document.getElementById("H_nextpage").style.display="none";}</script>

 

 

So if for example "H_tipitakaLinks" is missing in this document, it would not process further and not all would be hidden, while the ways are somehow strange. Ranking them helps, but not finally.

Share this post


Link to post
Share on other sites

Just create array of id ref, and apply davej classname 'showmore', and use his code

 window.onload=function(){           var id_ref_array = new Array("H_homage","F_footer","H_search","H_crumbtrail","H_copyright","F_read","H_docBy","H_docAuthor","H_tipitakaLinks","H_tipitakaID","H_docAuthorTrans","H_docAuthorTransInfo","H_docAuthorTransAlt","H_altFormat","H_nextpage")for(i=0;i<id_ref_array.length;i++)    {    if(document.getElementById(id_ref_array[i]));    document.getElementById(id_ref_array[i]).className='showmore';    }}       

Share this post


Link to post
Share on other sites

Oh, do you want to individually enable things or enable large lists of things? For individual items could try a generic version of the scheme I outlined above, but it presumes that everything is a block element, which could cause unexpected layout problems...

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>show hide anything</title><style>.showmore{display:none;}.showall{display:block;}</style><script>function showHide(link){var ele = link.previousSibling;while(ele.className!='showall'&&ele.className!='showmore'){// find the previous show/hide elementele = ele.previousSibling;;}if(ele.className=='showall'){link.innerHTML = '[Show More]';ele.className='showmore';}else{link.innerHTML = '[Hide]';ele.className='showall';}}</script></head><body><ul class="showmore"><li>Dog</li><li>Car</li><li>Tire</li></ul><a href="#" onclick="showHide(this);">[Show More]</a><img class="showmore" src="./images/Garden.jpg" width="200" alt="img"/><a href="#" onclick="showHide(this);">[Show More]</a><div class="showmore"><p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p></div><a href="#" onclick="showHide(this);">[Show More]</a><p class="showmore">I am a paragraph and a paragraph is not a block element</p></div><a href="#" onclick="showHide(this);">[Show More]</a></body></html>
Edited by davej

Share this post


Link to post
Share on other sites

Wohh! A night shift away I had no plan, and now so many solution. Thanks a lot.

 

Actually there are two things

 

One is the footer (with Info) to en-lapse collapse, that works (I guess) already great. And the other thing is the "Read only the real contexts" - mode, where all parts (menu, info's, ...) should be hidden. And they are good sorted in <div> ids.I have uploaded some pages with the current stage of my merely stroke of luck work. Maybe its useful to understand: Relentlessly (onclick - button for the "Read only the real contexts" - mode is in the upper right corner, the paper image - still some texts are not hidden proper. And the show and hide for the Terms are on the bottom, this part works well I guess)

 

Thanks a lot both of you! Incredible such a quick art of solution thinking, even with other ones codes.

 

mudita

Share this post


Link to post
Share on other sites

avoid changing styles through the DOM, using .style can lead to layout problems down the road. changing the className is where its at.

.expand{/*have your normal/fully expanded display css here*/}.inpand{/*have your minimized css here*/display:none;} 

The toggling function ("inpand_expand" in this example) doesn't need to know the Id of the elements. its called relative to the Dom's element. the only time you need to know the ids is when attaching the events and setting the defaults. in fact even then you don't need ids then if you go by classes (but you want to go by ids)

function inpand_expand(domEl){  var classes = domEl.className.split(" ");    ontoNextClass:  for(var c=0;c<classes.length;c++){    switch(classes[c]){      case "inpand":         classes[c] = "expand";        break;      case "expand":         classes[c] = "inpand";        break;      default:        continue ontoNextClass;    }    return domEl.className = classes.join(" ");  }  return domEl.className = classes.unshift("inpand").join(" ");}var addEvent = (function () {  var L = function (el, ev, fn) {    if (el.addEventListener) {      L = function (el, ev, fn) {        el.addEventListener(ev, fn, false);      };    } else if (el.attachEvent) {      L = function (el, ev, fn) {        el.attachEvent('on' + ev, fn);      };     } else {      L = function (el, ev, fn) {        el['on' + ev] = fn;      };    }    L(el, ev, fn);  };  return function (el, ev, fn) {    L(el, ev, fn);  };}());function setPand(){  var defaultC  =  (arguments[0])?"expand":"inpand";  var toggleTo = !(arguments[0])?"inpand":"expand";  ontoNextId:  for(var i=1;i<arguments.length;i++){    try{      var el;      if(Array.isArray(arguments[i]){        setInpand.apply(null,arguments[i].unshift(arguments[0]));      }else{        switch(typeof arguments[i]){          case "string":             el = document.getElementById(arguments[i]);addEvent(el,"click", function(){inpand_expand(this)});            var classes = el.className.split(" ");            classLoop:            for(var c=0;c<classes.length;c++){              if(classes[c] == defaultC){                continue ontoNextId;              }              if(classes[c] == toggleTo){                classes.splice(c--,1);                break classLoop;              }            }            el.className = classes.unshift(defaultC).join(" ");            break;            case "object":              //recursively calls both on keys and values              for(var key in arguments[i]){                setPand(arguments[0],key);                if(typeof arguments[i][key] == "string")                  setPand(arguments[0],arguments[i][key]);              }            break;            default:              //do nothing            break;        }      }    }catch(e){      //lower errors to warnings, this way you can still see the error,      // but they won't break the code (like they normally should)      console.warn(e);    }  }}var off = ["H_homage", "F_footer", "H_search", "H_crumbtrail", "H_copyright",                              "F_read", "H_docBy", "H_docAuthor", "H_tipitakaLinks", "H_tipitakaID",                              "H_docAuthorTrans", "H_docAuthorTransInfo", "H_docAuthorTransAlt",                              "H_altFormat", "H_nextpage"                           ];setPand(false,off); 

setPand is the function you'll use to set the defaults to all those elements with the ids as you wanted. you can pass the ids to setPand() on a per-argument-basis, as an Object, as an Array, or even any combination among those. in the example I stores all the ids in an array. 1st argument is a boolean to determine which state should be defaulted to (true for expand, false for inpand). now if an element with an id doesn't exist it won't break the code (instead issues a warning). This way you can define which elements will be hidden by default, and which elements are shown (but can be hidden) by default.

 

setPand and inpand_expand functions also work around any classes that were also defined in an element so as to not demolish any other styling you might have going on.

 

 

With a little tweaking you could merge mine and Davej's code to have his show more/show less link functionality

Share this post


Link to post
Share on other sites

You are freaking awesome! Thanks a lot Hadien.I thought that such as 2 kind of css, would be the most secure but had no idea how to manage. That would fit to it in its meaning and function I guess.Well there is already a lot of info here and I need to mention that I did not even know what css is 4 month ago not to speak about java... So 70% of the language I do not understand, but I guess I understand the different and function a little and its purpose. So lets see if I am able to "hack" this with my improvisation so that it might be working well.To work through all of this will be to much I guess.Thanks a lot. 'm Speak-less... so much hints an support.The code it self "function inpand..." is that a script to put in every html? (sorry for my question, as told, some HTML, a little css and the rest... since opening post here I guess.)

Edited by Johann

Share this post


Link to post
Share on other sites

Uhh Hadien, I guess that is out of my reach. :-) To less basic understanding. Maybe it's better to use first function off() and care that the id's are proper to the certain file. Guess that is something I can manage with my 3 tools skill "copie, paste and replace". davej code for this sample I could understand as I could try "when I adjust this... that happens" but here, I have to less imagination possibilities and miss the connecting key.Please apologies, this gift is to big that I can handle it at present times. Still that does not lessen the merits done by your generosity.

Edited by Johann

Share this post


Link to post
Share on other sites

Yes, sorry I was about to reply sooner yesterday, but ran into a small problem iPad randomly refreshing the page and losing my post, and I didn't want to type it all out again. When I wrote those code samples I gave you, I wasn't designing the code to be directly intuitive, especially to beginners.inland_expand(): this function uses the DOM and Array objects/methods and then uses some rather uncommon (and possibly confusing) syntax operands. Labels is a rarely documented, yet useful syntax in the JavaScript language which is used alongside "break" and "continue" (these two syntax usually seen without a label). It greatly simplifies how one can skip to specific points in nested loops. When you use continue with a label the continue will stop where ever it's at in the loop and jump up to where the label is defined and run the next iteration of that loop. A break with the label does a similar thing, instead it beaks out of the loop it's in, goes to where the label was defined, and then skips the loop it broke out of. It greatly simplifies code, but can be hard to wrap your head around, which is why I usually write my labels to look like you're reading a sentence. For instance, inside setPand when inside the nested for loops to iterate over the classes...from elements that where iterated. If you found an element that ALREADY had the proper default class, I wanted to skip the rest of the code in both for loops and just "continue onto the next ID". addEvent(): this function was written with browser compatibility and optimization in mind. The variables are non-descript and while some rather beautiful qualities of the language are being used, they aren't directly obvious to people who never took advantage of these qualities before. addEvent() is cleverly using both closure and memoization techniques to reduce any overhead in calling the function multiple times. It's using memoization to redefine itself once it's run for the first time. Doing so allows it to skip retesting the browser every time when the answer will always be the same.setPand() is using the ever so useful and important arguments variable, which is automatically controlled by javacript in relation to the function it's called in. By using the arguments Array, I was able to make setPand highly flexible with variety of datatypes you pass into it. Since at certain points I have the function call itself, it is a recursive function. Recursive functions can be quite elegant in logic, but it's also easy for one to cause infinite recursion (the primary reason I only recursively call on strings inside passed objects, since object are capable of pointing back on itself).And yes the toggle (inpand_expand) function is mostly encapsulated from the rest of the code so you can put it in almost any page, which will be using inpand and expand classes. Once you add it to a page, you just need to add in your code that will connect the function with the elements on the page.It's fine if you don't want to use my code, I had fun coding it and didn't stop to think if you would understand it. If you're curious as to how a piece of my code works or why I wrote it that way, feel free to ask a question.

Share this post


Link to post
Share on other sites

Dear Hadien,really no problem, please don't feel any stress with it or worry even if it is very careful and praiseworthy.

 

its not so much the code it self but I lack much of general knowledge how things are connected css-html-java and not even a real idea of DOM. That is my basic problem with it. Not to speak about the languages them selves, I am terrible in regard of languages and remembering, so I always use dictionaries. Programming is not different at all.So I had a relative ease to understand Davej sample and it took me an hour to have it integrated. It's that his sample includes css-hltm-java and so I could understand what it is doing and which parts and ways I can adopt to my environment.As told, I can see the great idea, the benefit and effort you did here and I am really ashamed that I am not capable to take and use this gift.For the general expand inpand I use this simple version:

<script>function off(){document.getElementById("H_homage").style.display="none";document.getElementById("F_footer").style.display="none";document.getElementById("H_search").style.display="none";document.getElementById("H_crumbtrail").style.display="none";document.getElementById("H_tipitakaLinks").style.display="none";document.getElementById("H_copyright").style.display="none";document.getElementById("H_altFormat").style.display="none";document.getElementById("F_read").style.display="none";document.getElementById("H_tipitakaID").style.display="none";document.getElementById("H_docAuthorTrans").style.display="none";document.getElementById("H_docAuthorTransInfo").style.display="none";document.getElementById("H_docAuthorTransAlt").style.display="none";document.getElementById("H_docBy").style.display="none";document.getElementById("H_docAuthor").style.display="none";document.getElementById("H_nextpage").style.display="none";}</script><script>function on()  {  location.reload()  }</script><script>function showHide(link){var article = link.previousSibling;while(article.nodeName!='ARTICLE'){// find the previous articlearticle = article.previousSibling;}if(article.className=='showall'){link.innerHTML = '<img src="http://zugangzureinsicht.org/html/img/more.png" alt="[show more]" />   [more]';article.className='showmore';}else{link.innerHTML = '<img src="http://zugangzureinsicht.org/html/img/hide.png" alt="[hide]" />   [hide]';article.className='showall';}}</script></head><body><div id="F_reload"><a onclick="on()" title='Cklick here to reload all informations of this page again.'><img width="50" src="http://zugangzureinsicht.org/html/img/read_en.png" alt="[reload all]" /></a></div><div id="F_read"><a onclick="off()" title='Click here to hide all informations except the discorse.'><img width="50" src="http://zugangzureinsicht.org/html/img/read_en.png" alt="[simple read]" /></a></div>

That is really simple and as the pages themselves are well structured it's relatively easy to change for a certain stock of pages an id with is not needed. To perfect running all over codes will cause some laziness in the general structure. So its somehow a good hint if you see a problem, better than if all run's smooth and the html content and structure it self is a mass.So here is my modest reward: Hard to Find and acknowledgment

Edited by Johann

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...