Click here to Skip to main content
12,506,198 members (53,779 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: Javascript
Using document.onclick event to hide a div popup in Javascript, overrides my other button click events. I tried a to capture the element id and then trigger the button click, but that didnt work either.
Any idea how to stop this and still have my button clicks work ?
Posted 2-Oct-12 7:03am
Teenustar1.2K
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

The trick is to use addEventListener. Adding a function in the HTML means the function is anonymous and can't be removed without setting onclick=''.

Using addEventListener means you can attach multiple handlers to an event. It also means that you can selectively remove them later.

I should point out that, AFAIK while I added them in the order func1, func2, the browser is under no obligation to execute them in this order.

<html>
<head>
<style>
</style>
 
<script>
function func1()
{
	// hello world! #1
	alert('func1');
}
function func2()
{
	// hello world! #2
	alert('func2');
	
	// get the button and remove the func1 handler
	// this means we'll see 2 alert boxes the first time round 'func1' then 'func2'
	// but any subsequent clicks will only trigger 1 alert-box 'func2'
	var btnElement = document.getElementById('myBtn');
	btnElement.removeEventListener('click', func1, false);
}
 
function myInit()
{
	var btnElement = document.getElementById('myBtn');
	btnElement.addEventListener('click', func1, false);
	btnElement.addEventListener('click', func2, false);
}
</script>
 
</head>
<body onload='myInit();'>
	<input id='myBtn' value='click me' type='button'/>
</body>
</html>
  Permalink  
Comments
Teenustar 2-Oct-12 15:18pm
   
This doesn't solve my problem if I use document.onclick
enhzflep 2-Oct-12 15:23pm
   
Yes, exactly - that was my point. Using onclick in the html to specify the event handler won't work.

Can you further elaborate on your problem and why this code is unsuitable?
Teenustar 2-Oct-12 15:38pm
   
I am trying to show/hide a div (like a popup window) on a button click. I need the div to hide, when user click anywhere else on the page.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Something like this perhaps?

<!DOCTYPE html>
<html>
<head>
<style>
/* just something to let us see where it is */
#showMe
{
    width: 200px;
    height: 75px;
    border: solid 3px red;
}
</style>
 
<script>
function byId(e){return document.getElementById(e);}
 
// flag used in the onmouseout and onmouse over listeners for the 'Show/Hide' btn
// used to ensure we only have 1 valid listener at a time. If mouse enters button, no need to listen for body mouse-clicks
// if mouse leaves button, no need to listen for button clicks
// (prevents both the btnClick and bodyClick functions firing when the pop-up is shown and the button is clicked - 2 events
// means the pop-up is closed then opened again - albeit too fast to see. The pop-up appears to remain motionless/unchanged.
var isVisible = false;
 
// handle cliks on the show/hide button
// just toggle the visible state
function btnClick(e)
{
    var tgt = document.getElementById('showMe');
    switch (isVisible)
    {
        case false:
            tgt.style.display = '';
            isVisible = true;
            break;
 
        default:
            tgt.style.display = 'none';
            isVisible = false;
    }
}
 
// handle clicks on the document body
//
// first make sure we don't come from a click on either the show/hide button or the popup itself.
// then re-attach the listener to the button and remove it from the body. - clicking the body with the popup close
// should do nothing. Clicking the button on the other hand, definitely should do something
function bodyClick(e)
{
    e = e || event;
    var tgt = document.getElementById('showMe');
    if ( ( e.srcElement != byId('showMe')) && (e.srcElement != byId('mBtn')) )
    {
        tgt.style.display = 'none';
        isVisible = false;
        document.removeEventListener('click', bodyClick, true);
        byId('mBtn').addEventListener('click', btnClick, true);
    }
}
 

function myInit()
{
        // fire the event whenever we click the show/hide btn
        byId('mBtn').addEventListener('click', btnClick, true);

        byId('mBtn').addEventListener(
                                        'mouseover',
                                        function()
                                        {
                                            if (isVisible)
                                            {
                                                document.removeEventListener('click', bodyClick, true);
                                                byId('mBtn').addEventListener('click', btnClick, true);
                                            }
                                        },
                                        true);
 

        byId('mBtn').addEventListener(
                                        'mouseout',
                                        function()
                                        {
                                            if (isVisible)
                                            {
                                                document.addEventListener('click', bodyClick, true);
                                                byId('mBtn').removeEventListener('click', btnClick, true);
                                            }
                                        },
                                        true);
}
 

</script>
 
</head>
    <body onload='myInit();'>
        <input id='mBtn' type='button' value='Show/Hide'/>
        <div id='showMe' style='display: none;'>
            I contain hidden content. Pop-me-up!
        </div>
        <br>
        <input type='button' onclick='alert("Hello World!");' value='test alert(...)'/>
    </body>
</html>
  Permalink  
Comments
Teenustar 3-Oct-12 10:10am
   
Perfect :)...thanks enhzflep.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160927.1 | Last Updated 2 Oct 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100