Jump to content

Help with Cookies, Functions (Arguments)


bgfuentes

Recommended Posts

I am adding "Like" buttons/counters on my site and I need help with achieving this without needing to make multiple copies of the function to make each button/counter unique. I imagine this can be done by passing different arguments to one function but I can't seem to figure it out.  I am new to this, so I appreciate your help!

Below is what I have so far, building from examples found here in W3.  As you can see, I duplicated the checkCookie function to work with 2 buttons -- brute-force method!  I don't think this is the right way to do it, especially that I need more than 10 buttons!

Thanks.

 

<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires=" + d.toGMTString();
  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;
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function checkCookie() {
  var likes=getCookie("LikesCount");
  if (likes != "") {

    likes++;
    setCookie("LikesCount", likes, 30);
    
  } else {
    setCookie("LikesCount", 0, 30);
    }
document.getElementById("Count").innerHTML = likes;
}

function checkCookie2() {
  var likes=getCookie("LikesCount2");
  if (likes != "") {

    likes++;
    setCookie("LikesCount2", likes, 30);
    
  } else {
    setCookie("LikesCount2", 0, 30);
    }
document.getElementById("Count2").innerHTML = likes;
}

</script>
</head>

<p>TEST</p>

<button onclick="checkCookie()" type="button" style="color: #ffffff; background-color: #3b5998;">&#128077; <b>Like</b></button>&nbsp;&nbsp;&nbsp;
<span id="Count"></span>

<br><br>

<button onclick="checkCookie2()" type="button" style="color: #ffffff; background-color: #3b5998;">&#128077; <b>Like</b></button>&nbsp;&nbsp;&nbsp;
<span id="Count2"></span>

</html>

Link to comment
Share on other sites

Do you realize that the like counts will go no further than the user's computer?

Cookies are only save on the currently used computer and not sent or shared with any others.

Based on this information, do you still want to pursue additional like button functions?

Link to comment
Share on other sites

Yes, I did realize that the cookies remain local to the users (I initially thought that switching from LocalStorage to cookies would address that issue).

In any case, I am still interested in how to accomplish above in the context of passing parameters to functions, which will be useful for other applications later. Thanks!

Link to comment
Share on other sites

Here is an example of how it could be done.

You can save the counts as a string or submit them in a form individually.
They could also be saved in local storage or cookies,
but again JS is not designed so that everyone the web would see total counts.  Only the user.

I had no images, but you should be able to supply your own.

The 'Clear Counts' button is optional and can be removed.
Note that it is the only 'button' with an associated ID value.

Only tested in FF & Chrome.  It should be tested further if you expect to use MSIE.

<!DOCTYPE html><html lang="en"><head>
<title> Multiple Button Counter </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!-- For: https://w3schools.invisionzone.com/topic/61942-help-with-cookies-functions-arguments/ -->

<style>
 button { background: yellow; font-weight: bold; }
 img { height: 3em;  width: 3em; }
</style>

</head><body>
<div id="btnLikes">
 <img src='' alt='image'><br>
 <button data-cnt="0">&#128077; Like</button> <span></span><br><br>
 <img src='' alt='image'><br>
 <button data-cnt="0">&#128077; Like</button> <span></span><br><br>
 <img src='' alt='image'><br>
 <button data-cnt="0">&#128077; Like</button> <span></span><br><br>
 <img src='' alt='image'><br>
 <button data-cnt="0">&#128077; Like</button> <span></span><br><br>
 <img src='' alt='image'><br>
 <button data-cnt="0">&#128077; Like</button> <span></span><br><br>
 <img src='' alt='image'><br>
 <button data-cnt="0">&#128077; Like</button> <span></span><br><br>
 <img src='' alt='image'><br>
 <button data-cnt="0">&#128077; Like</button> <span></span><br><br>
 <img src='' alt='image'><br>
 <button data-cnt="0">&#128077; Like</button> <span></span><br><br>
 <img src='' alt='image'><br>
 <button data-cnt="0">&#128077; Like</button> <span></span><br><br>
</div>
<button id='btnClear'>Clear Counts</button>
<pre id='demo'></pre>

<script>
console.clear();

const demo = document.getElementById('demo');
const btnSel = document.querySelectorAll('button');

function collectCounts() {
  const sel = document.querySelectorAll('#btnLikes button');
  let selCounts = [];
  for (let el of sel) {
    const count = el.dataset.cnt || 0;
    selCounts.push(count);
  } return selCounts;  // return array of counts
}
function clrCounts() {  // clear counts display for each button
  for (let btn of btnSel) {
    btn.dataset.cnt = 0; elemClear(btn.nextElementSibling);
  }
}

function init() {
  for (let btn of btnSel) { 
    btn.addEventListener('click', function (evt) {
      const count = evt.target.dataset.cnt || 0;
      evt.target.dataset.cnt = parseInt(count) + 1;
      evt.target.nextElementSibling.innerHTML = evt.target.dataset.cnt;
      demo.innerHTML = collectCounts().join(',');
    }, false);
  }
} init();

function elemClear(el) { while (el.firstChild) el.removeChild(el.firstChild); }
const btnClear = document.getElementById('btnClear')
btnClear.addEventListener('click', () => { elemClear(demo); clrCounts(); } );

</script>
</body></html>

Good Luck! :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...