Close menu by clicking outside itWhy don't self-closing script tags work?How do I detect a click outside an element?Trigger a button click with JavaScript on the Enter key in a text boxUse jQuery to hide a DIV when the user clicks outside of itOnblur event fires before another div's onclickAvoid dropdown menu close on click insideStating variables in the onClick attribute, and using multiple commands in onClickCannot display HTML stringReact - toggle display of one component from the onClick of another componentin Dropdown multilevel menu, submenu is not stable it is disappear when iam hover

Infinite past with a beginning?

The magic money tree problem

How do I create uniquely male characters?

What is the command to reset a PC without deleting any files

Is it possible to do 50 km distance without any previous training?

Could a US political party gain complete control over the government by removing checks & balances?

What would happen to a modern skyscraper if it rains micro blackholes?

Copenhagen passport control - US citizen

Can town administrative "code" overule state laws like those forbidding trespassing?

What typically incentivizes a professor to change jobs to a lower ranking university?

How to make payment on the internet without leaving a money trail?

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

New order #4: World

A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?

Is it possible to make sharp wind that can cut stuff from afar?

How does one intimidate enemies without having the capacity for violence?

Do airline pilots ever risk not hearing communication directed to them specifically, from traffic controllers?

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

Shell script can be run only with sh command

My colleague's body is amazing

"which" command doesn't work / path of Safari?

What do you call a Matrix-like slowdown and camera movement effect?

Why Is Death Allowed In the Matrix?

Why can't I see bouncing of a switch on an oscilloscope?



Close menu by clicking outside it


Why don't self-closing script tags work?How do I detect a click outside an element?Trigger a button click with JavaScript on the Enter key in a text boxUse jQuery to hide a DIV when the user clicks outside of itOnblur event fires before another div's onclickAvoid dropdown menu close on click insideStating variables in the onClick attribute, and using multiple commands in onClickCannot display HTML stringReact - toggle display of one component from the onClick of another componentin Dropdown multilevel menu, submenu is not stable it is disappear when iam hover






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have created a mobile menu that opens on clicking the hamburger button. At present I can only close the menu by clicking the hamburger button. What do I need to add to be able to close the menu by clicking elsewhere on the page?



Code below.



Apologies for the basic question! Thanks in advance for any help.



Jordan






 function myFunction() 
var x = document.getElementById("myLinks");
if (x.style.display === "block")
x.style.display = "none";
else
x.style.display = "block";


<div class="topnav">
<a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
<div id="myLinks">
<a class="sub">SHORT WALKS</a>
<a class="sub">DAY TRIPS</a>
<a class="sub">MULTI-DAY</a>
<a class="sub">MAP EXPLORER</a>
<a class="sub">TRAIL SEARCH AND FILTER</a>
<a class="sub">TRAIL ALERTS</a>
<a class="sub">ABOUT</a>
</div>
<a href="javascript:void(0);" class="icon" onclick="myFunction()"><i class="fa fa-bars"></i></a>
</div>












share|improve this question






























    0















    I have created a mobile menu that opens on clicking the hamburger button. At present I can only close the menu by clicking the hamburger button. What do I need to add to be able to close the menu by clicking elsewhere on the page?



    Code below.



    Apologies for the basic question! Thanks in advance for any help.



    Jordan






     function myFunction() 
    var x = document.getElementById("myLinks");
    if (x.style.display === "block")
    x.style.display = "none";
    else
    x.style.display = "block";


    <div class="topnav">
    <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
    <div id="myLinks">
    <a class="sub">SHORT WALKS</a>
    <a class="sub">DAY TRIPS</a>
    <a class="sub">MULTI-DAY</a>
    <a class="sub">MAP EXPLORER</a>
    <a class="sub">TRAIL SEARCH AND FILTER</a>
    <a class="sub">TRAIL ALERTS</a>
    <a class="sub">ABOUT</a>
    </div>
    <a href="javascript:void(0);" class="icon" onclick="myFunction()"><i class="fa fa-bars"></i></a>
    </div>












    share|improve this question


























      0












      0








      0








      I have created a mobile menu that opens on clicking the hamburger button. At present I can only close the menu by clicking the hamburger button. What do I need to add to be able to close the menu by clicking elsewhere on the page?



      Code below.



      Apologies for the basic question! Thanks in advance for any help.



      Jordan






       function myFunction() 
      var x = document.getElementById("myLinks");
      if (x.style.display === "block")
      x.style.display = "none";
      else
      x.style.display = "block";


      <div class="topnav">
      <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
      <div id="myLinks">
      <a class="sub">SHORT WALKS</a>
      <a class="sub">DAY TRIPS</a>
      <a class="sub">MULTI-DAY</a>
      <a class="sub">MAP EXPLORER</a>
      <a class="sub">TRAIL SEARCH AND FILTER</a>
      <a class="sub">TRAIL ALERTS</a>
      <a class="sub">ABOUT</a>
      </div>
      <a href="javascript:void(0);" class="icon" onclick="myFunction()"><i class="fa fa-bars"></i></a>
      </div>












      share|improve this question
















      I have created a mobile menu that opens on clicking the hamburger button. At present I can only close the menu by clicking the hamburger button. What do I need to add to be able to close the menu by clicking elsewhere on the page?



      Code below.



      Apologies for the basic question! Thanks in advance for any help.



      Jordan






       function myFunction() 
      var x = document.getElementById("myLinks");
      if (x.style.display === "block")
      x.style.display = "none";
      else
      x.style.display = "block";


      <div class="topnav">
      <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
      <div id="myLinks">
      <a class="sub">SHORT WALKS</a>
      <a class="sub">DAY TRIPS</a>
      <a class="sub">MULTI-DAY</a>
      <a class="sub">MAP EXPLORER</a>
      <a class="sub">TRAIL SEARCH AND FILTER</a>
      <a class="sub">TRAIL ALERTS</a>
      <a class="sub">ABOUT</a>
      </div>
      <a href="javascript:void(0);" class="icon" onclick="myFunction()"><i class="fa fa-bars"></i></a>
      </div>








       function myFunction() 
      var x = document.getElementById("myLinks");
      if (x.style.display === "block")
      x.style.display = "none";
      else
      x.style.display = "block";


      <div class="topnav">
      <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
      <div id="myLinks">
      <a class="sub">SHORT WALKS</a>
      <a class="sub">DAY TRIPS</a>
      <a class="sub">MULTI-DAY</a>
      <a class="sub">MAP EXPLORER</a>
      <a class="sub">TRAIL SEARCH AND FILTER</a>
      <a class="sub">TRAIL ALERTS</a>
      <a class="sub">ABOUT</a>
      </div>
      <a href="javascript:void(0);" class="icon" onclick="myFunction()"><i class="fa fa-bars"></i></a>
      </div>





       function myFunction() 
      var x = document.getElementById("myLinks");
      if (x.style.display === "block")
      x.style.display = "none";
      else
      x.style.display = "block";


      <div class="topnav">
      <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
      <div id="myLinks">
      <a class="sub">SHORT WALKS</a>
      <a class="sub">DAY TRIPS</a>
      <a class="sub">MULTI-DAY</a>
      <a class="sub">MAP EXPLORER</a>
      <a class="sub">TRAIL SEARCH AND FILTER</a>
      <a class="sub">TRAIL ALERTS</a>
      <a class="sub">ABOUT</a>
      </div>
      <a href="javascript:void(0);" class="icon" onclick="myFunction()"><i class="fa fa-bars"></i></a>
      </div>






      javascript html menu onclick






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 21 at 22:37









      Zobia Kanwal

      536420




      536420










      asked Mar 21 at 22:30









      jordanmillerjordanmiller

      154




      154






















          3 Answers
          3






          active

          oldest

          votes


















          1














          There are many ways, one if using a generic onclick event in a superior element.
          Here is an example:






          function myFunction() 
          var x = document.getElementById("myLinks");
          if (x.style.display === "block")
          x.style.display = "none";
          else
          x.style.display = "block";



          window.onclick = myFunction;

          <div class="topnav">
          <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
          <div id="myLinks">
          <a class="sub">SHORT WALKS</a>
          <a class="sub">DAY TRIPS</a>
          <a class="sub">MULTI-DAY</a>
          <a class="sub">MAP EXPLORER</a>
          <a class="sub">TRAIL SEARCH AND FILTER</a>
          <a class="sub">TRAIL ALERTS</a>
          <a class="sub">ABOUT</a>
          </div>
          <a class="icon" onclick="myFunction()"><i class="fa fa-bars">Menu</i></a>
          </div>





          Of course window isn't a good element to use because it polutes js namespace. Put this in an element which is above your menu and that covers the whole page.
          You can use a root div or something like that.






          share|improve this answer























          • You could use <body> instead of window

            – Chipster
            Mar 21 at 22:45






          • 1





            @Chipster tried, but at least in the snippet it didn't work. If you know how to get it to work, please feel free to edit my answer.

            – Nelson Teixeira
            Mar 21 at 22:50











          • Thanks @NelsonTeixeira, the window method works, though the issue is that clicking in the window will open the menu, rather than only when you click the menu button. Sorry, I should have included the CSS as it's a little difficult to see in the code snippet

            – jordanmiller
            Mar 21 at 22:54


















          0














          Like the previous answer said, there are many ways to solve this. An alternative way is utilize the focus and blur events. As the previous comment said, you might want to avoid polluting the global name space.



          Here is an implementation utilizing focus and blur events.






          function onClick(e) 
          if (myLinks.classList.contains('hidden'))
          myLinks.classList.remove('hidden');
          navMenu.focus();
          else
          myLinks.classList.add('hidden');
          navMenu.blur()



          function onBlur()
          myLinks.classList.add('hidden');


          var myLinks = document.getElementById("myLinks");
          var navMenu = document.querySelector('.topnav')
          var myBtn = document.getElementById('home');
          myBtn.addEventListener('click', onClick);
          navMenu.addEventListener('blur', onBlur);

          .topnav 
          border: 1px dashed blue;


          .sub
          display: block;


          .hidden
          display: none;

          <div class="topnav" tabindex="0">
          <a id="home" class="nt"><strong>NELSON TRAILS</strong></a>
          <div id="myLinks" class="hidden">
          <a class="sub">SHORT WALKS</a>
          <a class="sub">DAY TRIPS</a>
          <a class="sub">MULTI-DAY</a>
          <a class="sub">MAP EXPLORER</a>
          <a class="sub">TRAIL SEARCH AND FILTER</a>
          <a class="sub">TRAIL ALERTS</a>
          <a class="sub">ABOUT</a>
          </div>
          </div>








          share|improve this answer






























            0














            This method probably not the best (one with blur/focus is better imo) but there a lot of different ways to do it so here goes another one.






            function openModal()
            var x = document.getElementById('myLinks');
            if(x.style.display != 'block')
            x.style.display = 'block';
            window.addEventListener('click', closeMenu, capture: true);



            function closeMenu(event)
            var el = document.getElementById('myLinks');
            if(el.style.display == 'block' && event.target != el)
            window.removeEventListener('click', closeMenu, capture: true);
            el.style.display = 'none';


            div#myLinks
            display: none;

            <div class="topnav">
            <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
            <div id="myLinks">
            <a class="sub">SHORT WALKS</a>
            <a class="sub">DAY TRIPS</a>
            <a class="sub">MULTI-DAY</a>
            <a class="sub">MAP EXPLORER</a>
            <a class="sub">TRAIL SEARCH AND FILTER</a>
            <a class="sub">TRAIL ALERTS</a>
            <a class="sub">ABOUT</a>
            </div>
            <p class="icon" onclick="openModal()">Menu</p>
            </div>





            We need capture option for event listener so it wont fire after initial click. This method is much less poluting the window because our listener exists only when menu is open.



            Also you shouldn't use javascript:void(0) for preventing redirecting.
            What you should do is something like this:






            document.addEventListener('DOMContentLoaded', function()
            document.querySelectorAll('a.prevent-default').forEach(function(el, i)
            el.addEventListener('click', preventDefault);
            );
            );

            function preventDefault(event)
            event.preventDefault();

            <a href="google.com" class="my-class prevent-default">Can't go through me!</a>





            This will find of all a elements with class prevent-default and prevent redirecting. Use of href="javascript:void(0);" is something to leave in the past.






            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55290201%2fclose-menu-by-clicking-outside-it%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              There are many ways, one if using a generic onclick event in a superior element.
              Here is an example:






              function myFunction() 
              var x = document.getElementById("myLinks");
              if (x.style.display === "block")
              x.style.display = "none";
              else
              x.style.display = "block";



              window.onclick = myFunction;

              <div class="topnav">
              <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
              <div id="myLinks">
              <a class="sub">SHORT WALKS</a>
              <a class="sub">DAY TRIPS</a>
              <a class="sub">MULTI-DAY</a>
              <a class="sub">MAP EXPLORER</a>
              <a class="sub">TRAIL SEARCH AND FILTER</a>
              <a class="sub">TRAIL ALERTS</a>
              <a class="sub">ABOUT</a>
              </div>
              <a class="icon" onclick="myFunction()"><i class="fa fa-bars">Menu</i></a>
              </div>





              Of course window isn't a good element to use because it polutes js namespace. Put this in an element which is above your menu and that covers the whole page.
              You can use a root div or something like that.






              share|improve this answer























              • You could use <body> instead of window

                – Chipster
                Mar 21 at 22:45






              • 1





                @Chipster tried, but at least in the snippet it didn't work. If you know how to get it to work, please feel free to edit my answer.

                – Nelson Teixeira
                Mar 21 at 22:50











              • Thanks @NelsonTeixeira, the window method works, though the issue is that clicking in the window will open the menu, rather than only when you click the menu button. Sorry, I should have included the CSS as it's a little difficult to see in the code snippet

                – jordanmiller
                Mar 21 at 22:54















              1














              There are many ways, one if using a generic onclick event in a superior element.
              Here is an example:






              function myFunction() 
              var x = document.getElementById("myLinks");
              if (x.style.display === "block")
              x.style.display = "none";
              else
              x.style.display = "block";



              window.onclick = myFunction;

              <div class="topnav">
              <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
              <div id="myLinks">
              <a class="sub">SHORT WALKS</a>
              <a class="sub">DAY TRIPS</a>
              <a class="sub">MULTI-DAY</a>
              <a class="sub">MAP EXPLORER</a>
              <a class="sub">TRAIL SEARCH AND FILTER</a>
              <a class="sub">TRAIL ALERTS</a>
              <a class="sub">ABOUT</a>
              </div>
              <a class="icon" onclick="myFunction()"><i class="fa fa-bars">Menu</i></a>
              </div>





              Of course window isn't a good element to use because it polutes js namespace. Put this in an element which is above your menu and that covers the whole page.
              You can use a root div or something like that.






              share|improve this answer























              • You could use <body> instead of window

                – Chipster
                Mar 21 at 22:45






              • 1





                @Chipster tried, but at least in the snippet it didn't work. If you know how to get it to work, please feel free to edit my answer.

                – Nelson Teixeira
                Mar 21 at 22:50











              • Thanks @NelsonTeixeira, the window method works, though the issue is that clicking in the window will open the menu, rather than only when you click the menu button. Sorry, I should have included the CSS as it's a little difficult to see in the code snippet

                – jordanmiller
                Mar 21 at 22:54













              1












              1








              1







              There are many ways, one if using a generic onclick event in a superior element.
              Here is an example:






              function myFunction() 
              var x = document.getElementById("myLinks");
              if (x.style.display === "block")
              x.style.display = "none";
              else
              x.style.display = "block";



              window.onclick = myFunction;

              <div class="topnav">
              <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
              <div id="myLinks">
              <a class="sub">SHORT WALKS</a>
              <a class="sub">DAY TRIPS</a>
              <a class="sub">MULTI-DAY</a>
              <a class="sub">MAP EXPLORER</a>
              <a class="sub">TRAIL SEARCH AND FILTER</a>
              <a class="sub">TRAIL ALERTS</a>
              <a class="sub">ABOUT</a>
              </div>
              <a class="icon" onclick="myFunction()"><i class="fa fa-bars">Menu</i></a>
              </div>





              Of course window isn't a good element to use because it polutes js namespace. Put this in an element which is above your menu and that covers the whole page.
              You can use a root div or something like that.






              share|improve this answer













              There are many ways, one if using a generic onclick event in a superior element.
              Here is an example:






              function myFunction() 
              var x = document.getElementById("myLinks");
              if (x.style.display === "block")
              x.style.display = "none";
              else
              x.style.display = "block";



              window.onclick = myFunction;

              <div class="topnav">
              <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
              <div id="myLinks">
              <a class="sub">SHORT WALKS</a>
              <a class="sub">DAY TRIPS</a>
              <a class="sub">MULTI-DAY</a>
              <a class="sub">MAP EXPLORER</a>
              <a class="sub">TRAIL SEARCH AND FILTER</a>
              <a class="sub">TRAIL ALERTS</a>
              <a class="sub">ABOUT</a>
              </div>
              <a class="icon" onclick="myFunction()"><i class="fa fa-bars">Menu</i></a>
              </div>





              Of course window isn't a good element to use because it polutes js namespace. Put this in an element which is above your menu and that covers the whole page.
              You can use a root div or something like that.






              function myFunction() 
              var x = document.getElementById("myLinks");
              if (x.style.display === "block")
              x.style.display = "none";
              else
              x.style.display = "block";



              window.onclick = myFunction;

              <div class="topnav">
              <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
              <div id="myLinks">
              <a class="sub">SHORT WALKS</a>
              <a class="sub">DAY TRIPS</a>
              <a class="sub">MULTI-DAY</a>
              <a class="sub">MAP EXPLORER</a>
              <a class="sub">TRAIL SEARCH AND FILTER</a>
              <a class="sub">TRAIL ALERTS</a>
              <a class="sub">ABOUT</a>
              </div>
              <a class="icon" onclick="myFunction()"><i class="fa fa-bars">Menu</i></a>
              </div>





              function myFunction() 
              var x = document.getElementById("myLinks");
              if (x.style.display === "block")
              x.style.display = "none";
              else
              x.style.display = "block";



              window.onclick = myFunction;

              <div class="topnav">
              <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
              <div id="myLinks">
              <a class="sub">SHORT WALKS</a>
              <a class="sub">DAY TRIPS</a>
              <a class="sub">MULTI-DAY</a>
              <a class="sub">MAP EXPLORER</a>
              <a class="sub">TRAIL SEARCH AND FILTER</a>
              <a class="sub">TRAIL ALERTS</a>
              <a class="sub">ABOUT</a>
              </div>
              <a class="icon" onclick="myFunction()"><i class="fa fa-bars">Menu</i></a>
              </div>






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Mar 21 at 22:40









              Nelson TeixeiraNelson Teixeira

              3,95321943




              3,95321943












              • You could use <body> instead of window

                – Chipster
                Mar 21 at 22:45






              • 1





                @Chipster tried, but at least in the snippet it didn't work. If you know how to get it to work, please feel free to edit my answer.

                – Nelson Teixeira
                Mar 21 at 22:50











              • Thanks @NelsonTeixeira, the window method works, though the issue is that clicking in the window will open the menu, rather than only when you click the menu button. Sorry, I should have included the CSS as it's a little difficult to see in the code snippet

                – jordanmiller
                Mar 21 at 22:54

















              • You could use <body> instead of window

                – Chipster
                Mar 21 at 22:45






              • 1





                @Chipster tried, but at least in the snippet it didn't work. If you know how to get it to work, please feel free to edit my answer.

                – Nelson Teixeira
                Mar 21 at 22:50











              • Thanks @NelsonTeixeira, the window method works, though the issue is that clicking in the window will open the menu, rather than only when you click the menu button. Sorry, I should have included the CSS as it's a little difficult to see in the code snippet

                – jordanmiller
                Mar 21 at 22:54
















              You could use <body> instead of window

              – Chipster
              Mar 21 at 22:45





              You could use <body> instead of window

              – Chipster
              Mar 21 at 22:45




              1




              1





              @Chipster tried, but at least in the snippet it didn't work. If you know how to get it to work, please feel free to edit my answer.

              – Nelson Teixeira
              Mar 21 at 22:50





              @Chipster tried, but at least in the snippet it didn't work. If you know how to get it to work, please feel free to edit my answer.

              – Nelson Teixeira
              Mar 21 at 22:50













              Thanks @NelsonTeixeira, the window method works, though the issue is that clicking in the window will open the menu, rather than only when you click the menu button. Sorry, I should have included the CSS as it's a little difficult to see in the code snippet

              – jordanmiller
              Mar 21 at 22:54





              Thanks @NelsonTeixeira, the window method works, though the issue is that clicking in the window will open the menu, rather than only when you click the menu button. Sorry, I should have included the CSS as it's a little difficult to see in the code snippet

              – jordanmiller
              Mar 21 at 22:54













              0














              Like the previous answer said, there are many ways to solve this. An alternative way is utilize the focus and blur events. As the previous comment said, you might want to avoid polluting the global name space.



              Here is an implementation utilizing focus and blur events.






              function onClick(e) 
              if (myLinks.classList.contains('hidden'))
              myLinks.classList.remove('hidden');
              navMenu.focus();
              else
              myLinks.classList.add('hidden');
              navMenu.blur()



              function onBlur()
              myLinks.classList.add('hidden');


              var myLinks = document.getElementById("myLinks");
              var navMenu = document.querySelector('.topnav')
              var myBtn = document.getElementById('home');
              myBtn.addEventListener('click', onClick);
              navMenu.addEventListener('blur', onBlur);

              .topnav 
              border: 1px dashed blue;


              .sub
              display: block;


              .hidden
              display: none;

              <div class="topnav" tabindex="0">
              <a id="home" class="nt"><strong>NELSON TRAILS</strong></a>
              <div id="myLinks" class="hidden">
              <a class="sub">SHORT WALKS</a>
              <a class="sub">DAY TRIPS</a>
              <a class="sub">MULTI-DAY</a>
              <a class="sub">MAP EXPLORER</a>
              <a class="sub">TRAIL SEARCH AND FILTER</a>
              <a class="sub">TRAIL ALERTS</a>
              <a class="sub">ABOUT</a>
              </div>
              </div>








              share|improve this answer



























                0














                Like the previous answer said, there are many ways to solve this. An alternative way is utilize the focus and blur events. As the previous comment said, you might want to avoid polluting the global name space.



                Here is an implementation utilizing focus and blur events.






                function onClick(e) 
                if (myLinks.classList.contains('hidden'))
                myLinks.classList.remove('hidden');
                navMenu.focus();
                else
                myLinks.classList.add('hidden');
                navMenu.blur()



                function onBlur()
                myLinks.classList.add('hidden');


                var myLinks = document.getElementById("myLinks");
                var navMenu = document.querySelector('.topnav')
                var myBtn = document.getElementById('home');
                myBtn.addEventListener('click', onClick);
                navMenu.addEventListener('blur', onBlur);

                .topnav 
                border: 1px dashed blue;


                .sub
                display: block;


                .hidden
                display: none;

                <div class="topnav" tabindex="0">
                <a id="home" class="nt"><strong>NELSON TRAILS</strong></a>
                <div id="myLinks" class="hidden">
                <a class="sub">SHORT WALKS</a>
                <a class="sub">DAY TRIPS</a>
                <a class="sub">MULTI-DAY</a>
                <a class="sub">MAP EXPLORER</a>
                <a class="sub">TRAIL SEARCH AND FILTER</a>
                <a class="sub">TRAIL ALERTS</a>
                <a class="sub">ABOUT</a>
                </div>
                </div>








                share|improve this answer

























                  0












                  0








                  0







                  Like the previous answer said, there are many ways to solve this. An alternative way is utilize the focus and blur events. As the previous comment said, you might want to avoid polluting the global name space.



                  Here is an implementation utilizing focus and blur events.






                  function onClick(e) 
                  if (myLinks.classList.contains('hidden'))
                  myLinks.classList.remove('hidden');
                  navMenu.focus();
                  else
                  myLinks.classList.add('hidden');
                  navMenu.blur()



                  function onBlur()
                  myLinks.classList.add('hidden');


                  var myLinks = document.getElementById("myLinks");
                  var navMenu = document.querySelector('.topnav')
                  var myBtn = document.getElementById('home');
                  myBtn.addEventListener('click', onClick);
                  navMenu.addEventListener('blur', onBlur);

                  .topnav 
                  border: 1px dashed blue;


                  .sub
                  display: block;


                  .hidden
                  display: none;

                  <div class="topnav" tabindex="0">
                  <a id="home" class="nt"><strong>NELSON TRAILS</strong></a>
                  <div id="myLinks" class="hidden">
                  <a class="sub">SHORT WALKS</a>
                  <a class="sub">DAY TRIPS</a>
                  <a class="sub">MULTI-DAY</a>
                  <a class="sub">MAP EXPLORER</a>
                  <a class="sub">TRAIL SEARCH AND FILTER</a>
                  <a class="sub">TRAIL ALERTS</a>
                  <a class="sub">ABOUT</a>
                  </div>
                  </div>








                  share|improve this answer













                  Like the previous answer said, there are many ways to solve this. An alternative way is utilize the focus and blur events. As the previous comment said, you might want to avoid polluting the global name space.



                  Here is an implementation utilizing focus and blur events.






                  function onClick(e) 
                  if (myLinks.classList.contains('hidden'))
                  myLinks.classList.remove('hidden');
                  navMenu.focus();
                  else
                  myLinks.classList.add('hidden');
                  navMenu.blur()



                  function onBlur()
                  myLinks.classList.add('hidden');


                  var myLinks = document.getElementById("myLinks");
                  var navMenu = document.querySelector('.topnav')
                  var myBtn = document.getElementById('home');
                  myBtn.addEventListener('click', onClick);
                  navMenu.addEventListener('blur', onBlur);

                  .topnav 
                  border: 1px dashed blue;


                  .sub
                  display: block;


                  .hidden
                  display: none;

                  <div class="topnav" tabindex="0">
                  <a id="home" class="nt"><strong>NELSON TRAILS</strong></a>
                  <div id="myLinks" class="hidden">
                  <a class="sub">SHORT WALKS</a>
                  <a class="sub">DAY TRIPS</a>
                  <a class="sub">MULTI-DAY</a>
                  <a class="sub">MAP EXPLORER</a>
                  <a class="sub">TRAIL SEARCH AND FILTER</a>
                  <a class="sub">TRAIL ALERTS</a>
                  <a class="sub">ABOUT</a>
                  </div>
                  </div>








                  function onClick(e) 
                  if (myLinks.classList.contains('hidden'))
                  myLinks.classList.remove('hidden');
                  navMenu.focus();
                  else
                  myLinks.classList.add('hidden');
                  navMenu.blur()



                  function onBlur()
                  myLinks.classList.add('hidden');


                  var myLinks = document.getElementById("myLinks");
                  var navMenu = document.querySelector('.topnav')
                  var myBtn = document.getElementById('home');
                  myBtn.addEventListener('click', onClick);
                  navMenu.addEventListener('blur', onBlur);

                  .topnav 
                  border: 1px dashed blue;


                  .sub
                  display: block;


                  .hidden
                  display: none;

                  <div class="topnav" tabindex="0">
                  <a id="home" class="nt"><strong>NELSON TRAILS</strong></a>
                  <div id="myLinks" class="hidden">
                  <a class="sub">SHORT WALKS</a>
                  <a class="sub">DAY TRIPS</a>
                  <a class="sub">MULTI-DAY</a>
                  <a class="sub">MAP EXPLORER</a>
                  <a class="sub">TRAIL SEARCH AND FILTER</a>
                  <a class="sub">TRAIL ALERTS</a>
                  <a class="sub">ABOUT</a>
                  </div>
                  </div>





                  function onClick(e) 
                  if (myLinks.classList.contains('hidden'))
                  myLinks.classList.remove('hidden');
                  navMenu.focus();
                  else
                  myLinks.classList.add('hidden');
                  navMenu.blur()



                  function onBlur()
                  myLinks.classList.add('hidden');


                  var myLinks = document.getElementById("myLinks");
                  var navMenu = document.querySelector('.topnav')
                  var myBtn = document.getElementById('home');
                  myBtn.addEventListener('click', onClick);
                  navMenu.addEventListener('blur', onBlur);

                  .topnav 
                  border: 1px dashed blue;


                  .sub
                  display: block;


                  .hidden
                  display: none;

                  <div class="topnav" tabindex="0">
                  <a id="home" class="nt"><strong>NELSON TRAILS</strong></a>
                  <div id="myLinks" class="hidden">
                  <a class="sub">SHORT WALKS</a>
                  <a class="sub">DAY TRIPS</a>
                  <a class="sub">MULTI-DAY</a>
                  <a class="sub">MAP EXPLORER</a>
                  <a class="sub">TRAIL SEARCH AND FILTER</a>
                  <a class="sub">TRAIL ALERTS</a>
                  <a class="sub">ABOUT</a>
                  </div>
                  </div>






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 21 at 23:38









                  mmohammadmmohammad

                  531610




                  531610





















                      0














                      This method probably not the best (one with blur/focus is better imo) but there a lot of different ways to do it so here goes another one.






                      function openModal()
                      var x = document.getElementById('myLinks');
                      if(x.style.display != 'block')
                      x.style.display = 'block';
                      window.addEventListener('click', closeMenu, capture: true);



                      function closeMenu(event)
                      var el = document.getElementById('myLinks');
                      if(el.style.display == 'block' && event.target != el)
                      window.removeEventListener('click', closeMenu, capture: true);
                      el.style.display = 'none';


                      div#myLinks
                      display: none;

                      <div class="topnav">
                      <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
                      <div id="myLinks">
                      <a class="sub">SHORT WALKS</a>
                      <a class="sub">DAY TRIPS</a>
                      <a class="sub">MULTI-DAY</a>
                      <a class="sub">MAP EXPLORER</a>
                      <a class="sub">TRAIL SEARCH AND FILTER</a>
                      <a class="sub">TRAIL ALERTS</a>
                      <a class="sub">ABOUT</a>
                      </div>
                      <p class="icon" onclick="openModal()">Menu</p>
                      </div>





                      We need capture option for event listener so it wont fire after initial click. This method is much less poluting the window because our listener exists only when menu is open.



                      Also you shouldn't use javascript:void(0) for preventing redirecting.
                      What you should do is something like this:






                      document.addEventListener('DOMContentLoaded', function()
                      document.querySelectorAll('a.prevent-default').forEach(function(el, i)
                      el.addEventListener('click', preventDefault);
                      );
                      );

                      function preventDefault(event)
                      event.preventDefault();

                      <a href="google.com" class="my-class prevent-default">Can't go through me!</a>





                      This will find of all a elements with class prevent-default and prevent redirecting. Use of href="javascript:void(0);" is something to leave in the past.






                      share|improve this answer





























                        0














                        This method probably not the best (one with blur/focus is better imo) but there a lot of different ways to do it so here goes another one.






                        function openModal()
                        var x = document.getElementById('myLinks');
                        if(x.style.display != 'block')
                        x.style.display = 'block';
                        window.addEventListener('click', closeMenu, capture: true);



                        function closeMenu(event)
                        var el = document.getElementById('myLinks');
                        if(el.style.display == 'block' && event.target != el)
                        window.removeEventListener('click', closeMenu, capture: true);
                        el.style.display = 'none';


                        div#myLinks
                        display: none;

                        <div class="topnav">
                        <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
                        <div id="myLinks">
                        <a class="sub">SHORT WALKS</a>
                        <a class="sub">DAY TRIPS</a>
                        <a class="sub">MULTI-DAY</a>
                        <a class="sub">MAP EXPLORER</a>
                        <a class="sub">TRAIL SEARCH AND FILTER</a>
                        <a class="sub">TRAIL ALERTS</a>
                        <a class="sub">ABOUT</a>
                        </div>
                        <p class="icon" onclick="openModal()">Menu</p>
                        </div>





                        We need capture option for event listener so it wont fire after initial click. This method is much less poluting the window because our listener exists only when menu is open.



                        Also you shouldn't use javascript:void(0) for preventing redirecting.
                        What you should do is something like this:






                        document.addEventListener('DOMContentLoaded', function()
                        document.querySelectorAll('a.prevent-default').forEach(function(el, i)
                        el.addEventListener('click', preventDefault);
                        );
                        );

                        function preventDefault(event)
                        event.preventDefault();

                        <a href="google.com" class="my-class prevent-default">Can't go through me!</a>





                        This will find of all a elements with class prevent-default and prevent redirecting. Use of href="javascript:void(0);" is something to leave in the past.






                        share|improve this answer



























                          0












                          0








                          0







                          This method probably not the best (one with blur/focus is better imo) but there a lot of different ways to do it so here goes another one.






                          function openModal()
                          var x = document.getElementById('myLinks');
                          if(x.style.display != 'block')
                          x.style.display = 'block';
                          window.addEventListener('click', closeMenu, capture: true);



                          function closeMenu(event)
                          var el = document.getElementById('myLinks');
                          if(el.style.display == 'block' && event.target != el)
                          window.removeEventListener('click', closeMenu, capture: true);
                          el.style.display = 'none';


                          div#myLinks
                          display: none;

                          <div class="topnav">
                          <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
                          <div id="myLinks">
                          <a class="sub">SHORT WALKS</a>
                          <a class="sub">DAY TRIPS</a>
                          <a class="sub">MULTI-DAY</a>
                          <a class="sub">MAP EXPLORER</a>
                          <a class="sub">TRAIL SEARCH AND FILTER</a>
                          <a class="sub">TRAIL ALERTS</a>
                          <a class="sub">ABOUT</a>
                          </div>
                          <p class="icon" onclick="openModal()">Menu</p>
                          </div>





                          We need capture option for event listener so it wont fire after initial click. This method is much less poluting the window because our listener exists only when menu is open.



                          Also you shouldn't use javascript:void(0) for preventing redirecting.
                          What you should do is something like this:






                          document.addEventListener('DOMContentLoaded', function()
                          document.querySelectorAll('a.prevent-default').forEach(function(el, i)
                          el.addEventListener('click', preventDefault);
                          );
                          );

                          function preventDefault(event)
                          event.preventDefault();

                          <a href="google.com" class="my-class prevent-default">Can't go through me!</a>





                          This will find of all a elements with class prevent-default and prevent redirecting. Use of href="javascript:void(0);" is something to leave in the past.






                          share|improve this answer















                          This method probably not the best (one with blur/focus is better imo) but there a lot of different ways to do it so here goes another one.






                          function openModal()
                          var x = document.getElementById('myLinks');
                          if(x.style.display != 'block')
                          x.style.display = 'block';
                          window.addEventListener('click', closeMenu, capture: true);



                          function closeMenu(event)
                          var el = document.getElementById('myLinks');
                          if(el.style.display == 'block' && event.target != el)
                          window.removeEventListener('click', closeMenu, capture: true);
                          el.style.display = 'none';


                          div#myLinks
                          display: none;

                          <div class="topnav">
                          <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
                          <div id="myLinks">
                          <a class="sub">SHORT WALKS</a>
                          <a class="sub">DAY TRIPS</a>
                          <a class="sub">MULTI-DAY</a>
                          <a class="sub">MAP EXPLORER</a>
                          <a class="sub">TRAIL SEARCH AND FILTER</a>
                          <a class="sub">TRAIL ALERTS</a>
                          <a class="sub">ABOUT</a>
                          </div>
                          <p class="icon" onclick="openModal()">Menu</p>
                          </div>





                          We need capture option for event listener so it wont fire after initial click. This method is much less poluting the window because our listener exists only when menu is open.



                          Also you shouldn't use javascript:void(0) for preventing redirecting.
                          What you should do is something like this:






                          document.addEventListener('DOMContentLoaded', function()
                          document.querySelectorAll('a.prevent-default').forEach(function(el, i)
                          el.addEventListener('click', preventDefault);
                          );
                          );

                          function preventDefault(event)
                          event.preventDefault();

                          <a href="google.com" class="my-class prevent-default">Can't go through me!</a>





                          This will find of all a elements with class prevent-default and prevent redirecting. Use of href="javascript:void(0);" is something to leave in the past.






                          function openModal()
                          var x = document.getElementById('myLinks');
                          if(x.style.display != 'block')
                          x.style.display = 'block';
                          window.addEventListener('click', closeMenu, capture: true);



                          function closeMenu(event)
                          var el = document.getElementById('myLinks');
                          if(el.style.display == 'block' && event.target != el)
                          window.removeEventListener('click', closeMenu, capture: true);
                          el.style.display = 'none';


                          div#myLinks
                          display: none;

                          <div class="topnav">
                          <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
                          <div id="myLinks">
                          <a class="sub">SHORT WALKS</a>
                          <a class="sub">DAY TRIPS</a>
                          <a class="sub">MULTI-DAY</a>
                          <a class="sub">MAP EXPLORER</a>
                          <a class="sub">TRAIL SEARCH AND FILTER</a>
                          <a class="sub">TRAIL ALERTS</a>
                          <a class="sub">ABOUT</a>
                          </div>
                          <p class="icon" onclick="openModal()">Menu</p>
                          </div>





                          function openModal()
                          var x = document.getElementById('myLinks');
                          if(x.style.display != 'block')
                          x.style.display = 'block';
                          window.addEventListener('click', closeMenu, capture: true);



                          function closeMenu(event)
                          var el = document.getElementById('myLinks');
                          if(el.style.display == 'block' && event.target != el)
                          window.removeEventListener('click', closeMenu, capture: true);
                          el.style.display = 'none';


                          div#myLinks
                          display: none;

                          <div class="topnav">
                          <a href="#home" class="nt"><strong>NELSON TRAILS</strong></a>
                          <div id="myLinks">
                          <a class="sub">SHORT WALKS</a>
                          <a class="sub">DAY TRIPS</a>
                          <a class="sub">MULTI-DAY</a>
                          <a class="sub">MAP EXPLORER</a>
                          <a class="sub">TRAIL SEARCH AND FILTER</a>
                          <a class="sub">TRAIL ALERTS</a>
                          <a class="sub">ABOUT</a>
                          </div>
                          <p class="icon" onclick="openModal()">Menu</p>
                          </div>





                          document.addEventListener('DOMContentLoaded', function()
                          document.querySelectorAll('a.prevent-default').forEach(function(el, i)
                          el.addEventListener('click', preventDefault);
                          );
                          );

                          function preventDefault(event)
                          event.preventDefault();

                          <a href="google.com" class="my-class prevent-default">Can't go through me!</a>





                          document.addEventListener('DOMContentLoaded', function()
                          document.querySelectorAll('a.prevent-default').forEach(function(el, i)
                          el.addEventListener('click', preventDefault);
                          );
                          );

                          function preventDefault(event)
                          event.preventDefault();

                          <a href="google.com" class="my-class prevent-default">Can't go through me!</a>






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 22 at 0:59

























                          answered Mar 22 at 0:22









                          Alex KislukhinAlex Kislukhin

                          262




                          262



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55290201%2fclose-menu-by-clicking-outside-it%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현