1
<head>
<script>
$("body").on("contextmenu", "img", function(e) {
  return false;
}); 
</script>
</head>

<?php
session_start();
include 'connection.php';
include 'sessions.php';

$image_id = $_GET['id'];

$query = "SELECT * FROM medical_data WHERE md_id = '$image_id'";
$result = mysqli_query($con,$query) or die(mysqli_error($con));

if (mysqli_num_rows($result) > 0) 
{
while($row = mysqli_fetch_assoc($result)) 
{                           
$image = $row['md_pt_image'];
}                                  
}   

echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'" height="auto" width="auto"/><br>';        

?>

This is my code, I want display an image from database and disable right click on it. But the JS is not working, i still can right click on the image. Is it because I am using < img > in echo ? or my JS is wrong!?

Wocugon
  • 566
  • 2
  • 7
  • 22
  • Why you want to disable right click? As user is able to get it from console DOM also – Mayank Pandeyz Mar 18 '17 at 04:52
  • 1
    You need to wait until the document has completed loading. Look at wrapping your code in an `ready` function a la [this answer](http://stackoverflow.com/a/5618300/648350) – haxxxton Mar 18 '17 at 04:56
  • Or you can replace `body` with `document` (it should be `$(document).on`). The document reference is ready at the beginning (although the contents are not loaded at that time). But the `body` should be available only after its contents are loaded. – Hopeless Mar 18 '17 at 05:07

3 Answers3

3

As @haxxxton already said that you need to wrap your code in document.ready to make it work.

<script type="text/javascript">
$(document).ready(function(){
$('img').on('contextmenu', function(e) {
return false;
});
});
</script>

Another way of doing it with pure javascript is

<script type='text/javascript'>

function nocontext(e) {
  var clickedTag = (e==null) ? event.srcElement.tagName : e.target.tagName;
   if (clickedTag == "IMG") {
   return false;
   }
}
document.oncontextmenu = nocontext;

</script>
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42
1

Neel had a perfectly good answer and in fact I upvoted it.

Consider this a second implementation: You can use preventDefault();

function nocontext(e) {
  var clickedTag = (e==null) ? event.srcElement.tagName : e.target.tagName;
  if (clickedTag == "IMG") {
     e.preventDefault();
  }
}

document.oncontextmenu = nocontext;
John Vandivier
  • 2,158
  • 1
  • 17
  • 23
0

Just Use Like:

<div id="disabled"></div>

$(document).ready(function() {
    $("#disabled").on("contextmenu",function(e){
       return false;
    }); 
}); 

Working JS FIDDLE LINK

Sagar Arora
  • 1,743
  • 1
  • 10
  • 19