I've implemented a script that tracks the number of clicks on each link and arranges them based on this count...
Currently, everything is functioning correctly except when the <a>
tags are nested inside a div. In such cases, the script ignores the surrounding divs
, including any content or images/icons within them, and only displays the links themselves.
Is there a way to modify the script so that it considers and reorders the entire div rather than just the link?
Please review my current progress below:
function updateClicks(ele) {
const storage = window.localStorage.getItem(ele.innerHTML + " clicks");
if (storage === null) {
window.localStorage.setItem(ele.innerHTML + " clicks", "1");
} else {
var clicks = parseInt(window.localStorage.getItem(ele.innerHTML + " clicks")) + 1;
localStorage.removeItem(ele.innerHTML + " clicks");
window.localStorage.setItem(ele.innerHTML + " clicks", clicks);
}
}
function orderItems() {
var order = [];
var href = [];
var links = document.getElementById("links-list");
var link = links.getElementsByTagName("a");
for (i = 0; i < link.length; i++) {
href.push(link[i].href);
}
links = links.innerHTML.split("</a>");
document.getElementById("links-list").innerHTML = "";
for (i = 0; i < links.length - 1; i++) {
var lastChar = links[i].charAt(links[i].length - 1);
var clicks = parseInt(window.localStorage.getItem(lastChar + " clicks"));
if (isNaN(clicks)) {
clicks = 0;
}
order.push([lastChar, clicks, href[i]]);
}
order.sort(function(a, b) {
return a[1] - b[1]
});
order.reverse();
console.log(order)
for (i = 0; i < order.length; i++) {
document.getElementById("links-list").innerHTML += "<a href='" + order[i][2] + "' onclick='updateClicks(this)'>" + order[i][0] + "</a>";
}
}
.link-container {
display: inline-block;
}
.link-container a {
padding: 10px;
background-color: #c0c0c0;
}
.link-img {
width: 16px;
height: 16px;
}
<body onload="orderItems();">
<div id="links-list">
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/6ZpMxiG.png" />
<a href="#" onclick="updateClicks(this)">A</a>
</div>
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/sFUFOyO.png" />
<a href="#" onclick="updateClicks(this)">B</a>
</div>
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/M5a2gh8.png" />
<a href="#" onclick="updateClicks(this)">C</a>
</div>
<div class="card link-container">
<img class="link-img" src="https://i.imgur.com/mbrEuvR.png" />
<a href="#" onclick="updateClicks(this)">D</a>
</div>
</div>
</body>
I'm currently expanding my knowledge in JS and require this functionality for an ongoing project. Your assistance is greatly appreciated.