Search code examples
javascripthtmlonclicksetcookie

How to set onclick functions to multiple elements?


I am trying to use javascript to set the onclick property for my links. When the user clicks the link, I want to set a cookie.

Here is the code to set the cookie:

function setCookie(cookieName, cookieValue, cookiePath, cookieExpires){
    cookieValue = escape(cookieValue);
    if (cookieExpires == "") {
      var nowDate = new Date();
      nowDate.setMonth(nowDate.getMonth() + 6);
      cookieExpires = nowDate.toGMTString();
} if (cookiePath != "") {
  cookiePath = ";Path=" + cookiePath;
}
document.cookie = cookieName + "=" + cookieValue + 
  ";expires=" + cookieExpires + cookiePath;
}

function getCookieValue(cookieName)
{
var cookieValue = document.cookie;
var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
if (cookieStartsAt == -1)
{
  cookieStartsAt = cookieValue.indexOf(cookieName + "=");
}
if (cookieStartsAt == -1)
{
  cookieValue = null;
}
else
{
  cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
  var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
  if (cookieEndsAt == -1)
  {
     cookieEndsAt = cookieValue.length;
  }
  cookieValue = unescape(cookieValue.substring(cookieStartsAt,
     cookieEndsAt));
}
return cookieValue;
}

And now here is the code to set the onclick function:

var elements = document.getElementsByTagName('a');
   for(var i = 0, len = elements.length; i < len; i++) {
        elements[i].onclick = setCookie("workshop", elements[i].getAttribute("name"), "", "");
   }

I would like for the cookie value to be set as the name of the link. For example, if I have a link <a href="#" name="test2"> , I want the cookie to be set to "test2".

However, with this code, the cookie value keeps coming out to be the name attribute of the last < a > tag on the page (the last link). I want each link to have their own onclick function; not all of them to set the cookie to the same value. This way, once the user reaches the next screen, I will know which link they clicked to get there.

ANY HELP IS GREATLY APPRECIATED! THANKS AHEAD!


Solution

  • Use the addEventListener() function instead of an onclick event handler. Something like this should do what you want:

    var elements = document.getElementsByTagName('a');
    for (var i = 0, len = elements.length; i < len; i++) {
      elements[i].addEventListener("click", function() {
        setCookie("workshop", this.getAttribute("name"), "", "");
      });
    }