Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable mobile longpress context menu on specific elements

I have an image gallery with various controls. One of the controls is a basic delete function, to delete you click and hold for approx 1 second to get a confirmation asking if you want to delete. All works fine, it's just that on mobile devices it often causes the "Save Image As, etc" menu to pop up which has to be closed before the intended action can be performed.

I've read about various fixes but none of them seem to work with current versions of Chrome mobile on my Galaxy S5, and the most recent answer I could find was from 2013.

I found one saying that the context menu was it's own function, so I tried something like this:

    window.oncontextmenu = function(event) {
        event.preventDefault();
        event.stopPropagation();
        return false;
    };

But it did not prevent the context menu from showing on my S5. As I said, I'm hoping to find a solution to prevent it from coming up on certain items, not the entire window.

Thanks to Tasos for the answer

document.getElementById('yourElement').oncontextmenu = function(event) {
    event.preventDefault();
    event.stopPropagation(); // not necessary in my case, could leave in case stopImmediateProp isn't available? 
    event.stopImmediatePropagation();
    return false;
};
like image 980
SISYN Avatar asked Nov 21 '22 09:11

SISYN


1 Answers

I (re)post the answer here because at first, I haven't seen it was in the question :)

So juste use this code, with stopImmediatePropagation :

document.getElementById('yourElement').oncontextmenu = function(event) {
    event.preventDefault();
    event.stopPropagation(); // not necessary in my case, could leave in case stopImmediateProp isn't available? 
    event.stopImmediatePropagation();
    return false;
};
like image 103
fred727 Avatar answered May 14 '23 07:05

fred727