I have a snippet of jQuery code which I would like to add a new li element to my menu, and not have a href tag, but rather control the link through js.
Don't ask me why, I have my secret reasons :D
I am base64 encoding the link into a html attribute "data-link".
The onclick event should handle the redirect, but for some reason this line is failing
let encLink = jQuery(this).attr("data-link"); // returning undefined
This was working during development, but something has happened and now and I can't figure out what the issue is.
Any help appreciated.
jQuery(document).ready( function() {
const link = "https://www.google.com";
const text = "Link to google";
const encodedLink = btoa(link);
const ulSelector = "#menu-top-nav";
const mobileulSelector = ".mobile-only ul:first-child";
const newliElement = `<li data-link="${encodedLink}" style="cursor:pointer" class="menu-item jshref"><a>${text}</a></li>`;
let newLi = jQuery(ulSelector + " > li:first-child").after(newliElement);
let newLimobile = jQuery(mobileulSelector + " > li:first-child").after(newliElement);
jQuery(document).on("click", ".jshref", (evt) => {
let encLink = jQuery(this).attr("data-link");
console.log("encLink = " + encLink);
const href = atob(encLink); // !problem encLink is undefined
//window.location.href = href;
});
});