bgfuentes
-
Posts
3 -
Joined
-
Last visited
Content Type
Profiles
Forums
Events
Posts posted by bgfuentes
-
-
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!
-
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;">👍 <b>Like</b></button>
<span id="Count"></span><br><br>
<button onclick="checkCookie2()" type="button" style="color: #ffffff; background-color: #3b5998;">👍 <b>Like</b></button>
<span id="Count2"></span></html>
Help with Cookies, Functions (Arguments)
in JavaScript
Posted
Excellent! I still have a lot to learn. 😅
Appreciate taking the time to help me out. Thank you!