almai
4/12/2018 - 12:32 PM

Opt-out button for Google Tag Manager tracking codes

Opt-out button for Google Tag Manager tracking codes

<!-- If there's no jQuery installed on your website then uncomment the following script tag.
If you have access to the website then copy the script tag into its head but before the GTM script tag. -->
<!-- script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script -->

<script>
  function writeState(str, btn) {
    var txtStr = 'aktiviert',
        txtBtn = 'Jetzt deaktivieren';

    // Toggle content
    if (localStorage.getItem({{oos}})) {  // {{oos}} is a GTM variable that containt the string "optOutStatus"
      txtStr = 'deaktiviert';
      txtBtn = 'Jetzt aktivieren';
    }

    str.text(txtStr);
    btn.text(txtBtn);
  }

  jQuery(document).ready(function() {
    // Append opt-out button to WordPress article.
    var html = '<p id="optOut">Das Webtracking auf dieser Seite ist <b>deaktiviert</b>. <button class="et_pb_button et_pb_contact_submit">Jetzt aktivieren</button></p>';
    
    // Please change the selector to the element you want the button be appended to!
    jQuery('#main-content article .et_pb_row_10 .et_pb_text_inner').append(html);

    var obj = jQuery('#optOut'),
        str = obj.find('b'),
        btn = obj.find('button');

    if (obj.length === 0) { return; }
  
    // Some styling
    obj.css(
      {
        'borderTop' : '1px solid #ccc',
        'paddingTop' : '20px',
        'lineHeight' : '30px'
      }
    );

    btn.css('outline', 'none');

    // Update content
    writeState(str, btn);

    btn.click(function(e) {
      e.preventDefault();

      // Toggle opt-out state
      if (localStorage.getItem({{oos}})) {
        localStorage.removeItem({{oos}});
      } else {
        localStorage.setItem({{oos}}, true);
      }

      // Update content each time the state changes
      writeState(str, btn);
    });
  });
</script>