Click here to Skip to main content
15,891,621 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

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
<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>
 
Share this answer
 
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.
Something like this perhaps?

HTML
<!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>
 
Share this answer
 
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900