Implementing Basic and Fancy Show/Hide in MooTools 1.2

By  on  

One of the great parts of MooTools is that the library itself allows for maximum flexibility within its provided classes. You can see evidence of this in the "Class" class' implement method. Using the implement method, you can add your own methods to custom or core classes.

I've created a really basic example and more advanced example of implementing show and hide on the Element class. By implementing show and hide, I can call show() and hide() on any element of any type that I want!

Basic Example - MooTools JavaScript

//when the dom is ready...
window.addEvent('domready', function() {
	//time to implement basic show / hide
	Element.implement({
		//implement show
		show: function() {
			this.setStyle('display','');
		},
		//implement hide
		hide: function() {
			this.setStyle('display','none');
		}
	});
});

Basic Example - XHTML / Usage

<p>
	<strong>Basic: </strong><a href="javascript:$('blove').show();">Show</a> | <a href="javascript:$('blove').hide();">Hide</a><br />
	<img src="/demo/beatles-love.jpg" id="blove" />
</p>

As you can see, the links call the image element's show and hide methods.

Fancy Example - MooTools JavaScript

//when the dom is ready...
window.addEvent('domready', function() {
	//time to implement fancy show / hide
	Element.implement({
		//implement show
		fancyShow: function() {
			this.fade('in');
		},
		//implement hide
		fancyHide: function() {
			this.fade('out');
		}
	});
});

Fancy Example - XHTML / Usage

<p>
	<strong>Fancy: </strong><a href="javascript:$('blove2').fancyShow();">Show</a> | <a href="javascript:$('blove2').fancyHide();">Hide</a><br />
	<img src="/demo/beatles-love.jpg" id="blove2" />
</p>

Instead of the not-so-subtle show and hide that we used in the basic example, I've chosen to use a softer fade in and fade out effect. Implementing methods is that easy!

Recent Features

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

  • By
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

Incredible Demos

Discussion

  1. Very cool and a great idea of a script to put into your general bag of JS tricks (typically an enhancements.js script in my case). Love the rockage of Mootools lately in your blog ;)

    Only criticism is that you’re using inline JS to handle the events. This would be much nicer if the JS parsed the HTML for links with .show or .hide classes and apply it where ever they were.

    Normally this would be an obvious “duh”, but then again so is this script. If fledgling developers are discovering this for the first time I worry that they would not know to take that extra, but well worth, step during development.

  2. @Tim: I see your point but the usage wasn’t really the main point. That said, I could put more Moo in the header that looked something like:

    $('myanchor').addEvent('click', function() {
    $('correspondingElement').hide();
    }
    

    Thanks for reading!

  3. Oops, didn’t end that right:

    $('myanchor').addEvent('click', function() {
    $('correspondingElement').hide();
    });
    
  4. LOL, have to remember those ending );’s – always slightly tricky.

    Hey….thanks for writing! Love the posts you put through and on a daily basis too.

  5. It’s better than the simple effect display:none/block lol
    Thanks David ;)

  6. That looks to me like you are inventing the wheel again. There is a native Mootools method to fade elements.

    http://docs12b.mootools.net/Fx/Fx.Tween#Element:fade

  7. @Louis: Yes and no. Yes, I’m using the fade effect that’s already there, but my goal with the article is show how to implement a method. Instead of using fade, I could put a whole ton of effects in there.

  8. Yes, I understand David. The title confused me a little bit, but you are right.

    This is more like a pattern :)

  9. @Louis: No, it’s my bad. After your initial post, I thought to myself “probably not the best title.” Misleading. Oh well, hopefully this clears things up.

  10. elvis

    Hi, David.
    Is it possilbe to post how to make tooltips with mootools 1.2 please?
    Thanks for a great tut.

  11. @Elvis: I have that post already written but I have a trouble ticket into MooTools — part of what they’re doing is wrong.

  12. elvis

    Hi David.
    I just can’t figure it out how to use tooltips with 1.2.
    I can see you are still using 1.11 for your tool tips as well.
    I am looking forward when you figure it out.

  13. Louisk

    Nice script. I am wondering if you could help us out with the following. On the mootools demo page (1.1) when you click on the js code links to show the js code, it hides the other panes if their are open. I can get the script but it’s not working with 1.2, how to do this?

  14. peter

    Hi David, I’m just getting started with mootools and I really love your posts, they are most helpfull to me. (I’m having a hard time finding good info and tutorials….)

    I’m trying to extend this script with the following :
    Have table rows hide on the basis of selection criteria through checkboxes.

    Currently I have a simple version working, but it only hides the first corresponding row ID it finds in the table. All the others with the correct ID don’t hide.

    Another thing I’m trying to do is, when a row hides, have the others scroll up… but first I need to find how to pass multiple id’s to the function.

    Do I need to pass it as an array ?

  15. dazbot

    Hi David, just stumbled across this script, its fantastic. Could you tell me how I could make ‘hide’ default, then on clicking ‘show’ it errrrm shows the picture or whatever.

    • How can you make the div display=”hidden” onLoad work with the fancy version? The basic version is obvious, it toggles the display. But the fancy show doesn’t work like that, so a hidden div stays hidden…

  16. Jaime Schultz

    Hi David,
    I just read your blog about Implementing Basic and Fancy Show/Hide in MooTools 1.2. I have a question, since yours seems to work in all browsers, what could be the reason onChange hide/shows work in IE and not Firefox or safari?

  17. Ashley

    I’ve been looking for the same thing Liam mentioned and cannot find a slide combined with a fade. Here’s a perfect example:

    http://www.dynamicdrive.com/dynamicindex17/animatedcollapse.htm

    Of course, it’s written using JQuery. Has anyone seen a Moo version?

  18. @Ashley — write one! :) It wouldn’t be that difficult.

  19. I have done a few in Jquery too, Just having issues in mootools for some reason.

  20. Ashley

    You’ve got the fancy-shmancy blog with moo scattered about…you write one! :)

    Besides, I’m just a designer that lets you guys do all the hard work. LOL

    So, check back tomorrow? OK, fine, Wednesday…sheesh.

  21. Is there a way to put a duration on the fading in and out of the display element? The fade() only works on opacity it seems, and so when an item is faded out, it still shows the block height element. I’d like to be able to fade out (in a “fancy” way) an element’s display from “block” to “none”. Is that possible? So far in my tests it seems to only want to act as if there is no duration:

    //set the div to be invisible on load
    $('theDiv').setStyle('display','none');
    
    var myEffect = new Fx.Tween($('cotp_desc'), {
        property: 'display',
        duration: 2000, //set the duration of the fade
        transition: Fx.Transitions.Quad.easeIn
      });
    
    $('hideDesc').addEvent('click', function(event) {
        myEffect.start('none');
      });
    
      $('showDesc').addEvent('click',function(event){
        myEffect.start('block');
      });
    

    HTML:

    <a href="#" id="showDesc">Show Text</a> | <a href="#" id="hideDesc">Hide Text</a>)<br />
    
    <div id="theDiv">
    Some text
    </div>
    
  22. And, oops, the “cotp_desc” should really be “theDiv” on the second line of script.

  23. Hey Dave,

    Great tutorial, how can we make a div hide onload though?

    • Bryan

      I was wondering the same thing.
      I’d really love to have that effect.
      Any ideas?

    • Jay

      Div contents

      Jay

    • Bryan

      Woops.
      I meant, I’d love to have the effect of hiding a on page load.

  24. Hi, I need to animate a panel onload (like a login panel), but started without any interaction of the user, how can I do something like this ? I can’t find a property to change relative positioning for instance:

    position: relative; top:0px

    to

    position: relative; top:100px

    Can you help me ?

  25. Jay

    Sorry! (forgot to hide code with code tag)

    Div contents

    Jay

  26. Jay

    Shoot! I guess this site does not allow HTML, so here goes


    LT div id="idvalue" style="display=none;" GT
    Div Contents
    LT /div GT

    To show this just use show or fade(‘in’) or similar.

    Jay

  27. Poderia ser assim é muito melhor, otimo post.

      window.addEvent('domready', function()
      {
       //domready é o onload do mootools
          Element.implement(
          {
              fancyShow: function()
              {
                  this.fade('in');
                  this.setStyle('display','');
              },
              fancyHide: function()
              {
                  this.fade('out');
                  this.setStyle('display','none');
              }
          });
          $('element').fancyHide();//carrega primeiro o função  fancyHide para deixar os campos ocultos
      });
    
  28. I’ve been looking around for something like this and maybe I’ll end up using this one…

  29. Hy David

    I am using your code with dissolve and reveal. The effect is nice but sometimes when I click back to the all menu there are some divs that doesn’t reveals.
    The other problem is that the divs are shrinking I don’t want that. Just want to fade in fade out than hide the div. Wanting to replicate the jquery isotope or quicksand. I want to add filter functions to my site. I am a doctor and a website hobbyist so I am not a programmer. I rely only to my knowledge and others on the net.
    Thank you.

  30. glen hart

    Hi I’m trying to implement a similar kind of feature but for three different text div’s.

    However i only want one of the three text expansions to show at any one time. Is there a straight forward way of doing this? So that if you click on a new “text show” it closes the old ones?

    Any link would be much appreciated.

    Thankyou

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!