Show / hide DIV based on consent category

Have more questions? Submit a request

You have content you'd like to display or hide when a certain category of cookies is accepted or has not been accepted. For this you can use the following example:

First make sure you have your div has a class assigned to it. In the example below we're using Advertising category and a div called testdiv.

 

  function handle_consent_event(e) {
  var consent = e.detail || { necessary: true };

  var elements = document.querySelectorAll(".testdiv"); //put the class if the div you want to hide here
  elements.forEach(function (el) {
    // no consent yet or advertising not accepted, hide element
    if (!consent || !consent.advertising) {
      if (el.getAttribute("src")) {
        el.style.display = "none";
				var div = document.createElement('div');
			div.classList.add('cf-div-class');
        var btn = document.createElement("button");
				btn.classList.add('cf-button-class'); // adding class
        btn.innerHTML = "Please Accept marketing cookies to watch this video.";
        var click = function () {
          CookieFirst.acceptCategory("advertising");
          window.location.reload();
        };
        btn.addEventListener("click", click);
        btn.setAttribute("data-accept-category", "advertising");
        el.before(btn);
				el.before(div);
        var src = el.getAttribute("src");
        el.setAttribute("data-src", src);
        el.setAttribute("src", "");
      }
    } else {
      el.style.display = "block";
if(el.parentElement) {
el.parentElement.querySelectorAll("[data-accept-category]").forEach(function(btn) {
btn.remove();
});
} 
      var src = el.getAttribute("data-src");
      if (src) {
        el.setAttribute("src", src);
        el.setAttribute("data-src", "");
      }
    }
  });
}

window.addEventListener("cf_consent", handle_consent_event);
window.addEventListener("cf_consent_loaded", handle_consent_event);

  

Articles in this section

Was this article helpful?
0 out of 6 found this helpful
Share