Is there any way to apply condition for showing Javascript or Jquery code in HTML Template ?
Like, if there's any data-id attribute containing "no-copy" value inside body tag, some javascript code will be apply.
For Example, If theres any id with the name "no-copy", some javacript code block will be apply in the theme.
If I explain it with more easily, I have some js code for not copying text/content from my site. And also for disable ctrl U and right button click. I want to apply them in my code, but conditionally. If users add data-id="no -copy" attributr inside body tag, my code (disable right button, select text etc.) will be apply or activate. Otherwise these code won't work.
Here's my simple approach:
let = document.getElementById("divId").getAttribute("data-no-copy");
function customAlert(message){
$('[data-no-copy="active"]').html(message).fadeIn(300).delay(2000).fadeOut(400);
};
document.addEventListener("contextmenu", function(event){
event.preventDefault();
customAlert('Right Click is Disabled');
}, false);
<style type="text/css">
#divId {
max-width: 300px;
background-color: #333;
color: #fff;
font-size: 15px;
text-align: center;
border-radius: 2px;
padding: 10px;
position: fixed;
z-index: 1;
right: 5%;
bottom: 20px;
display: none;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<body id="divId" data-no-copy="active"></body>
How I can activate this code only when users will add data-id="no -copy" attributr inside body tag. Not always activate.
CodePudding user response:
You can check for the data-attribute value, like I did here on my example, and if the data-value match your string (ex., 'active') you can trigger the routines to avoid right click and copy, like this example:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#divId {
max-width: 300px;
background-color: #333;
color: #fff;
font-size: 15px;
text-align: center;
border-radius: 2px;
padding: 10px;
position: fixed;
z-index: 1;
right: 5%;
bottom: 20px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body id="divId" data-no-copy="active">
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<script>
let no_copy = document.getElementById("divId").getAttribute("data-no-copy");
if(no_copy == 'active') {
document.addEventListener("contextmenu", function(event){
event.preventDefault();
alert('Right Click is Disabled');
}, false);
$(document).ready(function() {
$('body').bind('copy', function(event) {
event.preventDefault();
alert('Copy is Disabled');
});
});
}
</script>
</body>
</html>