2

I am handling mousedown & oncontextmenu events to prevent text & image selection, right click and drag. The code is as follows -

<body oncontextmenu="return false;" onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false"> 
    <input type="text" name="testInput" id="testInput">
</body>

I guess the problem is it is also preventing the focus on input elements, as I am preventing default & returning false for onmousedown event, so it is not letting control switch to input focus, so I cant type any thing inside it. I tried to debug it by following code.

<script type="text/javascript">
    $(function(){
        $( "#testInput" ).on("focus",function(){
           console.log("input focused");
        });
    });
</script>

When I removed the onmousedown attribute from body, it is giving me the desired message on cosole.

any help... Thanks in advance.

Pramod
  • 2,828
  • 6
  • 31
  • 40

1 Answers1

1

You can check if the mousedown/contextmenu event is happening on any inside element and allow the default action if so and if not prevent the default action by using below

document.getElementsByTagName("div")[0].addEventListener("mousedown",function(e){
    if(e.target.id=="testInput"){

    } else{
      e.preventDefault();
    }

});

document.getElementsByTagName("div")[0].addEventListener("contextmenu",function(e){
    if(e.target.id=="testInput"){

    } else{
      e.preventDefault();
    }

});

Check the Fiddle

Chakravarthy S M
  • 608
  • 6
  • 15
  • but its body mousedown/contextmenu event will be called whenever I will try it on inner elements, and from body itself it is returning, not letting control to handle inner element's mousedown/contextmenu. – Pramod Sep 16 '14 at 09:09
  • you can use document.getElementsByTagName("body")[0] instead of div – Chakravarthy S M Sep 16 '14 at 09:24