Saturday 6 March 2021

How to test if contextmenu is open or displayed?

I have a page with a few pre tags in it containing computer code. I have a mouseover event listener, which highlights all the code in the pre tag. I also have it remove the highlighting on a mouseout event. Works real well if you use the keyboard to copy (ctrl-C).

But if you want to right-click and copy from the context menu, there is a problem. The moment the mouse enters the context menu, it triggers the mouseout event of the pre tag.

I need a way to test if the context menu is currently open or displayed. Then I can cancel removing the highlighting. Is there a way to test if the context menu is open or displayed?

I don't want anything jquery, please.

My final alternative to this problem might be the oncontextmenu, but I don't know how I would find out if it closes. Unless I try an event listener for the mouseout event of the context menu, if posible.

Here's my code so far:

window.onload = function(){

    function selectText(element) {
        var range, selection;

        if(window.getSelection) {
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(element);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }

    function unSelectText() {
        window.getSelection().removeAllRanges();
    }

    preTags = document.getElementsByTagName('PRE');

    for(var i = 0; i < preTags.length; i++) {
        preTags[i].onmouseover = function() {selectText(this)};
        preTags[i].onmouseout = function() {unSelectText(this)};
    }

    codeTags = document.getElementsByTagName('CODE');

    for(var i = 0; i < codeTags.length; i++) {
        codeTags[i].onmouseover = function() {selectText(this)};
        codeTags[i].onmouseout = function() {unSelectText(this)};
    }
};


from How to test if contextmenu is open or displayed?

No comments:

Post a Comment