0

I have recently made a website that uses basic javascript to make a counter (as well as html and CSS to make graphics) and now I want to include a component that allows the counter to go up even if the page is refreshed. This is a big project that will allow people to vote on memes in the free code camp earth facebook group and will prevent people from flooding the site with memes all the time - it's part of the Free code Camp Sunday Funnies community initiative.

Currently, when the page is refreshed, the counter goes back to zero.

Here is the context that is vital so that you can see how different my specific questions are than other ones! Firstly, here is my code (again, all you need to do is post this in notepad, I prefer visual code editor because it autoformats):

#Fbanner1 {
  position: absolute;
  top: 0;
  right: 0%



  }    
  #Fbanner2 {
      position: absolute;
      top: 0;
      left: 0%;


  }    
    #banner { 
       position: absolute; 
      top: 0%;
       left:0%;

}



        #hook {
            font-family: 'VT323', monospace;
            font-size: 30px;
            text-align: center;
            font-variant: small-caps;
            border-style: double solid;
            border-color:black;
            background-color:blue;
            transform: translateX(425px);

        }
        h1 {
            font-family: 'Nova Mono', monospace;
            font-size: 50px;
            text-align: center;
            transform: translateX(-5px);
        }

        body {
            background-color: green;

        }

        section {
            display: flex;
            flex-direction: row;
        }

        #main {
            font-family: 'Nova Mono', monospace;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            justify-content: space-around;
            text-align: center;
            position: absolute;
            top: 8px;
            transform:translateY(45px);
        }

    </style>

<div id="banner">
    <div id="banner-content">
        <title>Free Code Camp Sunday Meme Award</title>
<div id="instruct"><h4 id="Hook" >!click to choose the meme of legend!</h4>
</div></div>
    </div>
 </div>
</head>
<div id="Fbanner2"><p> <img height="100" width="100" 
src=".\images\fccLogo.png" alt=""></p>     </div>
<div id="Fbanner1"><p> <img height="100" width="100" 
src=".\images\fccLogo.png" alt=""></p>     </div>
<div id="main-content">
<body>

    <div id="main">
         <div id="titleF"><h1> Sunday Funnies Meme Award </h1></div>
        <section>

            <h2> 1st place
                <figure>
                    <img src=".\images\meme1.jpg" 
onclick="incrementThumb('1st')" width=200 height=200>
                     <p id="1st">0</p>
                    <h2>
                        <figcaption> Alert: dank meme found! </figcaption>
                </figure>
                </h2>

                <h2> 2nd place
                    <figure>
                        <img src=".\images\meme1.jpg" 
onclick="incrementThumb('2nd')" width=200 height=200>
                        <p id="2nd">0</p>
                        <h2>
                            <figcaption> Getting warmer.... </figcaption>
                    </figure>
                    </h2>

                     <h2> 3rd place
                         <figure>
                             <img src=".\images\meme1.jpg" 
onclick="incrementThumb('3rd')" width=200 height=200>
                             <p id="3rd">0</p>
                            <h2>
                                <figcaption> A small ripple effect...
</figcaption>
                        </figure>
                        </h2>

                    </section>

                    <footer>                
            <h2> Honorable Mention
                <section>
                    <figure>
                        <img src=".\images\meme1.jpg" 
 onclick="incrementThumb('HM1')" width=200 height=200>
                        <p id="HM1">0</p>
                        <h2>
                            <figcaption> Worth an eyebrow raise...
</figcaption>
                    </figure>
                </section>
                </h2>
                <h2> Hononorable Mention
                    <section>
                        <figure>
                            <img src=".\images\meme1.jpg" 
onclick="incrementThumb('HM2')" width=200 height=200>
                             <p id="HM2">0</p>
                             <h2>
                                      <figcaption> Worth an eyebrow raise...
 </figcaption>
                         </figure>
                     </section>
                     </h2>
         </footer>
     </div>


            <script type="text/javascript">
                function incrementThumb(value){
                   var currentValue = 
document.getElementById(value).innerHTML; 
                   //console.log("typeof" + typeof(currentValue)); 
                    //console.log("1" + currentValue);
                   if (currentValue === undefined || currentValue === "NaN" 
|| currentValue === '') {
                       currentValue = 0;
                       //console.log("0" + currentValue);

                   }
                    //console.log("2" + currentValue);

                   var newValue = parseInt(currentValue) + 1;
                 //console.log("3" + newValue);

                   document.getElementById(value).innerHTML= newValue;
                   localStorage.setItem(newValue);} 

                function DataSaver ()


               </script>


 </body> </div></div>


</html>

I have done intensive research on different ways to do this:

How to use local storage I

how to use local storage"> How to use local storage II

conflicting information on using cookies

Here is a similar method described in stack overflow, but I don't know how to apply it to my specific situation that involves a counter: Stack overflow research confusing one about cookies in addition (or instead of?) using local storage)

Here is an example of using local storage and an example that works! (see below, but you will have to copy and paste the info into notepad) step-by-step example

MDN local storage instruction doe snot make sense in this context:

MDN

Now that you have the context above, also how this is dealing with a counter variable and not a bunch of numbers, and I thought this is what I would do but I do not know how to set the item when it starts at zero and will change in the future. Here is the code, as described step by step, by Tod Motto:

   <textarea class="localstorage"></textarea>
    <button class="clear">Clear localStorage</button>
    <button class="empty">Empty localStorage</button>
<script>
      (function () {

        // Grab the textarea
        var demo = document.querySelector('.localstorage');

        // localStorage feature detect
        function supportsLocalStorage() {
          return typeof (Storage) !== 'undefined';
         }

    // Run the detection with inverted expression
    if (!supportsLocalStorage()) {

      // Change the value to inform the user of no support
      demo.value = 'No HTML5 localStorage support, soz.';

    } else {

      // Try this
      try {

            // Set the interval and autosave every second
            setInterval(function () {
              localStorage.setItem('autosave', demo.value);
            }, 1000);

          } catch (e) {

            // If any errors, catch and alert the user
            if (e == QUOTA_EXCEEDED_ERR) {
             alert('Quota exceeded!');
            }
          }

          // If there is data available
          if (localStorage.getItem('autosave')) {

            // Retrieve the item
            demo.value = localStorage.getItem('autosave');
          }

          // Clear button, onclick handler
          document.querySelector('.clear').onclick = function () {
            demo.value = '';
            localStorage.removeItem('autosave');
          };

           // Empty button, onclick handler
          document.querySelector('.empty').onclick = function () {
            demo.value = '';
            localStorage.clear();
          };

        }

      })();
    </script>

SKIP TO HERE IF YOU WANT TO SEE THE BRIEF VERSION OF THE EXPLANATION TO THE QUESTION

I understand that I need to set and get info and I assume that this info would be the counter, but

A. I dont know if that is possible (if I need to use cookies also); there is mixed reviews online about the different methods...

B. If I need to use WAMP (I am not asking how to use WAMP, just if I do...based on my research it seems like this is not neccesary)

C.If I can do this with a counter (maybe I cannot...and in that case anyone that is working with a popular meme site probably would like to know also to not try and do this)

D. Just as important, what do I set in situations like this with a counter (I am trying to build my skill base by doing projects, so I can use up less of your time.

My own example would be something like this:

localstorage.setitem(0, ++)

(I assume this because you are adding a value each time..also this is a snip it out of context but hopefully can be inserted in the Tod Mottos code above.

Jackal21
  • 19
  • 7
  • the MDN website for local storage is not showing up as a link and I do not know why so here is the link: https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage This comment helps clarify my links above. – Jackal21 Feb 27 '18 at 14:27
  • You should clean up the code block and only show the parts relevant to the question. (ie the javascript). Most people would just tldr – HollyLeaves Feb 27 '18 at 14:32
  • I've made it bold so you can look at what is relevant and skim over what is not, as I know everyone is very busy already. All the info is needed in the context, otherwise I am told that I am not being specific enough. – Jackal21 Feb 27 '18 at 14:38

1 Answers1

3

If the data you want to save has to be shared between users of the site then it isn't possible without some type of server-side technology. Easiest to learn and set up would probably be PHP (although I dislike it). There are other options too but set up and learning the language might be hard.

IF the counter data is unique to each user you can use either cookies or localstorage but it can easily be tampered with by the user. Cookie data is simpler to set and get and can be easily done with the following code:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

The code above is from here where you can learn more about cookies.

LiefdeWen
  • 566
  • 2
  • 14
  • Exactly this. If you want all users to see the exact same counter with its count shared amongst all user, you would need to use a server side programming language and store the count in some database. If not, you can use the localStorage. – minitauros Feb 27 '18 at 14:33
  • Would you reccomend using a local developer environment such as WAMP? and then I would be able to use cookies? – Jackal21 Feb 27 '18 at 14:41
  • Here is the link for WAMP so you can have more info: http://www.wampserver.com/ (more context of what I am possibly gonna work with) – Jackal21 Feb 27 '18 at 14:42
  • Wamp is a web server that can do stuff like compile PHP but cookies is something that is built into browsers so you can use cookies without WAMP or any web server. Personally if I was doing a small site like this I wouldn't use Wamp and access just via file if I didn't have access to a server side technology. – LiefdeWen Feb 27 '18 at 14:47