@@ -15,6 +15,9 @@ define(function (require, exports, module) {
1515 // if user is logged in we show the profile menu, otherwise we show the login menu
1616 let isLoggedIn = false ;
1717
18+ // this is to handle document click events to close popup
19+ let documentClickHandler = null ;
20+
1821 const defaultLoginData = {
1922 welcomeTitle : "Welcome to Phoenix Code" ,
2023 signInBtnText : "Sign in to your account" ,
@@ -68,6 +71,12 @@ define(function (require, exports, module) {
6871 $popup = null ;
6972 isPopupVisible = false ;
7073 }
74+
75+ // we need to remove document click handler if it already exists
76+ if ( documentClickHandler ) {
77+ $ ( document ) . off ( "mousedown" , documentClickHandler ) ;
78+ documentClickHandler = null ;
79+ }
7180 }
7281
7382 /**
@@ -100,6 +109,29 @@ define(function (require, exports, module) {
100109 }
101110 }
102111
112+ /**
113+ * this function is responsible to set up a click handler to close the popup when clicking outside
114+ */
115+ function _setupDocumentClickHandler ( ) {
116+ // remove any existing handlers
117+ if ( documentClickHandler ) {
118+ $ ( document ) . off ( "mousedown" , documentClickHandler ) ;
119+ }
120+
121+ // add the new click handler
122+ documentClickHandler = function ( event ) {
123+ // if the click is outside the popup and not on the profile button (which toggles the popup)
124+ if ( $popup && ! $popup [ 0 ] . contains ( event . target ) && ! $ ( "#user-profile-button" ) [ 0 ] . contains ( event . target ) ) {
125+ closePopup ( ) ;
126+ }
127+ } ;
128+
129+ // this is needed so we don't close the popup immediately as the profile button is clicked
130+ setTimeout ( function ( ) {
131+ $ ( document ) . on ( "mousedown" , documentClickHandler ) ;
132+ } , 100 ) ;
133+ }
134+
103135 /**
104136 * Shows the sign-in popup when the user is not logged in
105137 * @param {Object } loginData - Data to populate the template (optional)
@@ -148,6 +180,8 @@ define(function (require, exports, module) {
148180 positionPopup ( ) ;
149181 }
150182 } ) ;
183+
184+ _setupDocumentClickHandler ( ) ;
151185 }
152186
153187 /**
@@ -200,6 +234,8 @@ define(function (require, exports, module) {
200234 positionPopup ( ) ;
201235 }
202236 } ) ;
237+
238+ _setupDocumentClickHandler ( ) ;
203239 }
204240
205241 /**
0 commit comments