Is there any way to conditionally apply JavaScript or jQuery code in an HTML Template?
For example, if a data-id attribute with the value "no-copy" is found inside the body tag, certain JavaScript code will be applied.
To explain it more simply, I have JavaScript code that prevents text/content copying from my site and disables ctrl+U and right-click. I want to implement these functionalities in my code but only conditionally. If users add a data-id="no-copy" attribute inside the body tag, my code (to disable right-click and text selection) will be activated. Otherwise, these features won't work.
Here's a simplified approach:
let noCopy = 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 can I ensure that this code is activated only when users add the data-id="no-copy" attribute inside the body tag, and not always active?