Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining click and touchstart events not working

Tags:

javascript

I have a website that I'm trying to make functional on mobile as well. However, when I combine click and touchstart events for PC and tablets respectively, neither works(Clicking on the element the events are attached to aren't firing). Can anyone explain how I should go about fixing this? Here's an example of one element not working, the pen has the entire project.

HTML

<div id="menu">
    <h1>MENU</h1>
</div>
<div class="dropdown hidden">
    <ul>
        <li id="home_navlink">Home</li>
        <li id="about_navlink">About Me</li>
        <li id="work_navlink">My Work</li>
        <li id="contact_navlink">Contact Me</li>
    </ul>
</div>

JS

let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];
menu.addEventListener("click touchstart", function(){
    if(dropdown.classList.contains("showing")){
        dropdown.classList.remove("showing");
        dropdown.classList.add("hidden");
    }
    else{
        dropdown.classList.remove("hidden");
        dropdown.classList.add("showing");
    }
})

Pen

like image 796
Robert Avatar asked Jan 31 '23 01:01

Robert


1 Answers

Fetch the menu using javascript:

let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];

Declare a handler function as a function reference:

let clickHandler = function() {
    if (dropdown.classList.contains("showing")) {
        dropdown.classList.remove("showing");
        dropdown.classList.add("hidden");
    } else {
        dropdown.classList.remove("hidden");
        dropdown.classList.add("showing");
    }
}

Assign it to the click event:

menu.addEventListener("click", clickHandler);

And then check for touch event handler and assign a function for touchstart:

if ('ontouchstart' in window) {
    menu.addEventListener("touchstart", function() {
        var touchHndl = function() {
            //call the clickHandler actually
            clickHandler();
            //remove the touchend haldler after perform
            this.removeEventListener(touchHndl)
        }
        //attach a handler for touch end when you are in touchstart event
        this.addEventListener(touchHndl);
    });
}

So you were asking about a code segment in plain javascript, hope it helps. :)

like image 156
Koushik Chatterjee Avatar answered Feb 02 '23 16:02

Koushik Chatterjee