Fellow Stranger Fellow Stranger -4 years ago 50
Javascript Question

Converting hide/show function in mootools to pure javascript

I have the following function found in a SO answer:

function toggleTooltip(id) {
var e = document.id(id);
if( !e.toggleCallback ) {
e.toggleCallback = function() { toggleTooltip(id); };
if(e.style.display=='block') {
document.removeEvent('click', e.toggleCallback);
} else {
document.addEvent('click', e.toggleCallback);

On click it shows a specific element and then on click anywhere it hides it. A working example can be found here.

I like to use this as a pure javascript function (i.e. no mootools dependency), but I don't really understand how I'd turn the functions
to normal javascript.

Any help would be much appreciated.

Answer Source

You can do it like so:

// Might want to use DOMContentLoaded event instead of load.
window.addEventListener('load', function() { 
  document.querySelectorAll('a.tooltip').forEach(function(link) {
    var tooltip = document.getElementById(link.id + '_tooltip'),
      callback = function(e) {
        if (tooltip.style.display === 'block') {
          tooltip.style.display = 'none';
          document.removeEventListener('click', callback);
        } else {
          tooltip.style.display = 'block';
          document.addEventListener('click', callback);
    link.addEventListener('click', callback);
<a class="tooltip" id="link1" href="#">Show tooltip</a>
<div style="display:none" id="link1_tooltip">Click anywhere to dismiss</div>

Take a look at:

Revised jsfiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download