Show/Hide with Hide On Click Anywhere

I have a div that acts as a tooltip, and a link to show this tooltip. This part works fine.

<div class="tooltip">
     <span class="tooltip_help">
        <a onclick="toggleTooltips('tooltip1');" title="Tip">
            <img src="/ca/images/general/tooltip.png" alt="tooltip icon" title="Tip" align="absmiddle" border="0" />
        </a>
    </span> 
    <div id="tooltip1" class="tooltip_box">
        <span>
           tip text here.
        </span>
    </div>
</div> 

What I'm trying to do is set is so that it will hide with a click anywhere on the page (including inside of the div itself). I'm pretty close to having it, but it sometimes requires double clicks, and sometimes will show itself based on a click anywhere on the page. This is with mootools.

<script language="javascript" type="text/javascript">
function toggleTooltips(id) {
    var e = document.id(id);
    if(e.style.display=='block') {
        e.style.display='none';
        document.removeEvent('click', function() {
            toggleTooltips(id);
        });
    } else {
        e.style.display='block';
        document.addEvent('click', function() {
            toggleTooltips(id);
        });
    }
}
</script>

Any help would be appreciated.


I'm no mootools expert, but I'd imagine that you need to call addEvent and removeEvent with the exact same function - not two functions that do the same thing. My guess is that mootools can't remove the click-listener because it's looking for a function that hasn't actually been registered. Ie it's looking for function A, but the function you registered is function B. They do the same thing, but they aren't the same function.

The result is that the click-listener on the document is never removed, and instead toggles the element with every click - and a new toggle-function is added each time too. Once you've clicked a few times, clicking anywhere in the document results in the element toggling back and forth X number of times. If X is an odd number, it seems to work as expected. If it's even, it won't have any apparent effect.

Try this

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

I'd also advise you to not use the onclick attribute, since you're already using mootools. Instead, set up an event listener to fire when the document has loaded. Then use that to find the elements that need toggling, and set everything up there.

Edit: Here's what I mean: http://jsfiddle.net/au32j/1/

链接地址: http://www.djcxy.com/p/83952.html

上一篇: 将函数绑定到Twitter Bootstrap模式关闭

下一篇: 单击任意位置时显示/隐藏并隐藏