What is the best way to implement a conditional data-attribute tag in order to trigger JavaScript functionality?

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?

Answer №1

If you want to prevent right-clicking and copying on your webpage, you can utilize data-attributes to trigger certain actions when a specific value is present. For instance, in the example below, the data-value 'active' is used to disable right-click and copy functionalities:

<!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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When pressed, the button changes color to a vibrant shade of blue, and not just a simple outline

I'm experiencing an issue with a button that turns blue when the user holds onto it for a while on mobile. You can see an example in the image below: https://i.sstatic.net/VmnZ8.png Adding ::selected or outline did not resolve the problem as the ent ...

The menu bar created from getJSON is not displaying the jQuery UI CSS styles as expected

I have been working on creating a jQueryUI menubar using JSON data. The JSON data is successfully being converted into valid HTML, but the menubar does not display with the desired styling. It appears as an unstyled unordered list rather than a styled menu ...

Tips for storing an array of strings in a JSON file using Javascript

Is it possible to save an array of strings to a JSON file using Node.js? const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; example.json [ "a", "b&q ...

What is the best way to navigate a carousel containing images or divs using arrow keys while maintaining focus?

Recently, I have been exploring the Ant Carousel component which can be found at https://ant.design/components/carousel/. The Carousel is enclosed within a Modal and contains multiple child div elements. Initially, the arrow keys for navigation do not work ...

Is there a simpler method for making multiple posts using an AJAX JS loop?

My form is quite extensive and uses AJAX to save. The JavaScript functions are stored in an external file and structured like this: function milestone09() { $.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#milestone09').serialize( ...

Passing arguments from the server to the client

Here is some code that I am working on which includes a dropdown and a JavaScript function being called from the server side. I am having trouble passing a parameter to the JavaScript function. Can anyone help me resolve this issue? Server-side code: Pa ...

Svelte Material UI Circular Progress Indicator encountering issues

I'm having trouble getting the Svelte Material UI Circular Progress indicator to function properly. I attempted to implement it in my project initially, and then decided to try it out in Code Sandbox using the provided code from the documentation. How ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...

Include some extra margin or padding to ensure the section is visible below the fixed navbar

I have implemented smooth scrolling using scroll-behavior: smooth in my CSS. The navigation bar is sticky, and when I click on a menu item, it takes me to the designated section. The issue I am facing is that the section goes under the sticky navbar. I wo ...

Error message in nodejs: Content-type specified is invalid (status code: 415)

I am seeking guidance on how to send form data with headers using the request module. Within my code, I have a function called getToken that makes a POST request with headers and form data. The response data from this request is then used to make another ...

Having difficulty transferring data from a JSON file on a different domain to a variable using Ajax

As a beginner in Ajax, I am currently exploring the use of Ajax Cross domain functionality to fetch data. The Ajax function is triggered from test.php, which then calls stats.php to request the desired data. The content of Stats.php: <?php $data = ...

Adjust the size of the logo as the user scrolls

Currently, I am implementing a JavaScript feature that allows my logo to shrink when the user scrolls down and grow when they scroll up. To achieve this effect, I am utilizing the jQuery functions addClass and removeClass. However, I have encountered som ...

Position the Twitter, Facebook, and LinkedIn sharing buttons in alignment

I've tried various methods to align the Facebook share button with other social media buttons, but I haven't been successful so far. There seems to be a slight pixel difference. Any suggestions? <div style="float:left; vertical-align:top"> ...

Ajax is invoked only one time

The system is set up to display a follow button and an unfollow button. Clicking the follow button should make the unfollow button appear, and vice versa. Currently, when you click "follow", the database updates and the follow button disappears while the ...

Bursting at the seams: concealed issues

I am currently facing an issue with a facebook like button placed in the caption section of a slideshow div, located at the far bottom right corner. The problem arises when the 'post to wall' prompt pops up below the like button, but is cut off d ...

What is the best method for sending a JavaScript variable to the server and back again?

I'm currently working on a JavaScript project where I need to build a string. Let's say, for the sake of this example: var cereal = 'my awesome string'; There's also a button on my webpage: <button id="send" type="submit" nam ...

What is the best way to extract a particular key value from a JSON object?

I am completely new to the world of APIs and just starting out with JavaScript. My goal is to retrieve the status of a server from a server hosting panel using an API. In order to achieve this, I need to log in by making a request to /API/Core/Login, extra ...

JQuery isn't functioning properly on dynamically generated divs from JavaScript

I'm currently tackling an assignment as part of my learning journey with The Odin Project. You can check it out here: Despite creating the divs using JavaScript or jQuery as specified in the project requirements, I am unable to get jQuery's .hov ...

Is there a way to confirm that a file has been chosen for uploading prior to form submission, by utilizing the jquery validator?

I have a section on my website where users can upload files. I am trying to implement validation to ensure that a file has been selected before the form is submitted. Currently, I am using the jQuery form validator plugin for handling form validations. Th ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...