Search code examples
javascriptjquerycookiesdrupal-7

Button onclick and save cookie on Drupal 7


I have a Drupal 7 local website, that has an article and a popup on the first page that leads to that article. In that article I also have a button and I want when the button is clicked by a user, the website to "remember" the user and not show the popup again. I thought I could change the text of the button and store it as a cookie. This is the code for the button:

<button id="test" value="test" onclick="Press()">Press Here</button>
<script>
function Press() {
    var test= document.getElementById("test");
    test.innerHTML="Thank you";
    document.cookie = "Inner"= + test.value +"; expires=Fri, 5 Aug 2016 01:00:00 UTC;";}
</script>

And this is the code of the external js file that handles the popup:

      function openColorBox(){

if (document.cookie.length != 0){
   var buttonvaluearray = document.cookie.split("=");
   document.getElementById("test").innerHTML = buttonvaluearray[1];
}

if (test.innerHTML != "Thank you"){
        document.getElementById("popup").style.visibility = "visible";
        document.onclick= function(){
        document.getElementById("popup").style.visibility = "hidden";
    }
  }
}
    setTimeout(openColorBox, 5000);

But when I load the page, the popup shows as usual, but the text of the button changes immediately from "Press here" to "0; Drupal.toolbar.collapsed". I am a new web developer so I am sure something is wrong with the code I used either for the cookie creation/testing or the if statement of the external javascript file, but I can't spot the mistake(s). Any suggestions or opinions?


Solution

  • Case closed! All I had to do is to use localStorage from JavaScript, at the first script, and test it afterwards at the external js file in order to create the popup!