0

trying to get my burger icon to show the mobile menu from hidden to block with "display", code works on desktop with chrome simulator but not on the actual mobile device. my website is www.rikuzit.co.il

window.onclick = function(event){
    var burger = document.getElementById("burgerIcon");
    var mobileMenu = document.getElementById("mobileMenu");


if(event.target == burger){
    alert("burger was pressed");
        console.log(event.target);
        mobileMenu.style.display = "block"; 
    } else {    
        alert("clicked outside burger");
        console.log(event.target);
        mobileMenu.style.display = "none";
    }
}

i expect that when the button is tapped the menu should appear.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
YuRa44
  • 19
  • 4

3 Answers3

1

As shown in this answer, it's better to use touchstart for mobile devices:

window.ontouchstart = function(event){
    var burger = document.getElementById("burgerIcon");
    var mobileMenu = document.getElementById("mobileMenu");


if(event.target == burger){
    alert("burger was pressed");
        console.log(event.target);
        mobileMenu.style.display = "block"; 
    } else {    
        alert("clicked outside burger");
        console.log(event.target);
        mobileMenu.style.display = "none";
    }
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • ok, it worked but now, how can i check if the user tapped outside the mobileMenu so to close it? i've tried the same with "window" $(window).on('click touchstart', function() { $('#mobileMenu').css('display','none'); how can i check "if the user tapped anything but the 'mobile menu'"? is there something like " != "? – YuRa44 Feb 01 '19 at 06:04
  • I think you misunderstood my answer - you don't need jQuery. Simply replace `onclick` with `ontouchstart` and it will work. I will edit my answer. – Jack Bashford Feb 01 '19 at 06:05
  • My new problem is that when the "mobileMenu" appears and i tap on it, the "else" statement get's into action, so i tried to do if(event.target == burger || event.target == mobileMenu){mobileMenu.style.display = "block";} else { display:none};, i it did not work, do you have any ideas about how to make the mobile stay in "display:block" when i tap it? and why " || event.target == mobileMenu" do not work? – YuRa44 Feb 01 '19 at 06:27
  • ok i figured out that when i click the "mobileMenu" sometimes it's a "li" being selected, and sometimes it's "a", only when i click on the border of the div(mobileMenu) the event is the div being touched. – YuRa44 Feb 01 '19 at 07:01
0

You can do something like this

window.onclick = eventHandler
window.ontouch = eventHandler


function eventHandler(event){
   ...
}
0

(copied Shubham Chaudhary's answer) i hope this should work

window.onclick = eventHandler
window.ontouch = eventHandler


function eventHandler(event){
...
}