Sorting `divs` based on the number of user clicks in JavaScript: A simple guide

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.

Answer №1

Here is a method for monitoring click counts and organizing divs accordingly:

// To begin, the 'cnt' values in the 'divs' array could be set using local storage:
const
  list=document.getElementById("links-list"),
  divs=[...list.querySelectorAll(".card")];
divs.forEach(e=>e.cnt=0)

list.onclick=ev=>{
  if (ev.target.tagName!=="A") return;
  ev.target.closest(".card").cnt++;
  divs.sort((a,b)=>a.cnt-b.cnt)
   .forEach(el=>list.append(el))
  console.log(divs.map(e=>e.textContent.trim()+e.cnt).join(","))
}
.link-container {
  display: inline-block;
  border:1px solid grey;
}

.link-img {
  width: 16px;
  height: 16px;
}
<body">

<div id="links-list">
  <div class="card link-container">
    <img class="link-img" src="https://i.imgur.com/6ZpMxiG.png" />
    <a href="#">A</a>
  </div>

  <div class="card link-container">
    <img class="link-img" src="https://i.imgur.com/sFUFOyO.png" />
    <a href="#">B</a>
  </div>

  <div class="card link-container">
    <img class="link-img" src="https://i.imgur.com/M5a2gh8.png" />
    <a href="#">C</a>
  </div>

  <div class="card link-container">
    <img class="link-img" src="https://i.imgur.com/mbrEuvR.png" />
    <a href="#">D</a>
  </div>

</div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up a custom global variable in nuxt.js using vuetify

As I work on developing my app with Nuxt, I find myself frustrated by the need to constantly write an if statement in my pages using this.$Vuetify.breakpoint.name == 'xs' for handling responsiveness. Instead, I want to create my own variable for ...

Restoring styles back to the default CSS settings

I am currently working on creating visualizations using D3, and one challenge that I have encountered is the need to define a lot of styles within my code instead of in my CSS where I would prefer them to be. This necessity arises mainly to support transi ...

Discovering the scroll position in Reactjs

Utilizing reactjs, I am aiming to manage scroll behavior through the use of a `click` event. To start, I populated a list of posts using `componentDidMount`. Next, upon clicking on each post in the list using the `click event`, it will reveal the post de ...

Prevent financial disagreement by utilizing jQuery carefully

While I'm sure this question has been asked in a similar form before, my searches for the $ sign did not return any results here. I have already built a large system and heavily utilized jQuery, using $ as a reference. Now, I don't want to rever ...

React.js not displaying image

Here's my App.js File I am trying to display an image from the MongoDB database. Click here to view the image stored in MongoDB The images are stored as Binary data in MongoDB How can I display the image on the React page? import React,{useState} fr ...

The error `Error occurred when rendering: Users' data cannot be mapped` indicates a problem with the rendering process

Utilizing useSWR for data retrieval from an endpoint and attempting to display all returned data, I encounter the following error: unCaught (in promise) fetchedUsers.map is not a function uncaught TypeError: fetchedUsers.map is not a function The provided ...

Exploring the functionality of the $.each jQuery iterator. Can someone clarify the distinctions between these two methods?

Having vertices as an array of google.maps.LatLng objects means that they should return latlng points. The first code snippet works perfectly fine, however, I encounter issues when using the second one. // Iterate over the vertices. for (var index =0; ind ...

How to implement various middlewares in Express.js depending on the current environment using NODE_ENV?

My dilemma involves utilizing two different middlewares based on NODE_ENV: router1 for production and router2 for testing and development environments. I'm currently using the following code snippet: if( process.env.NODE_ENV === 'prod' ) { ...

Is there a way to trigger an AJAX request right before I leave the page or unload it?

When the window is about to be unloaded, an AJAX request is sent to a specific URL including the recent tracking ID and the time spent on the page in seconds. However, the behavior I am experiencing is an alert displaying [object Object]. ...

Tips for relocating a popup window''s position

A situation has arisen in my application where a popup window is opened with the following code: function newPopup(url, windowName) { window.open(url,windowName,'height=768,width=1366,left=10,top=10,titlebar=no,toolbar=no,menubar=no,location=no,d ...

How can you handle undefined values in the query object parameter when using Mongoose's Find function?

Alright: Sound.find({ what: req.query.what, where: req.query.where, date: req.query.date, hour: req.query.hour}, function(err, varToStoreResult, count) { //perform some actions }); Let's consider a scenario where only req.query.what has a ...

Shadow effect is present under every cell in the table row

I am struggling to create an HTML table with proper vertical spacing between rows and a shadow effect beneath each row. Unfortunately, the shadow always ends up overlapping other table content. I have tried adjusting the positioning of elements and setti ...

Experiencing difficulties with toggling the visibility of div elements when an onchange event occurs

I am experiencing some difficulties triggering an on-change event in the department drop-down field and I'm not certain if I've written it correctly. The error message indicates: Uncaught TypeError: Cannot read property 'style' of null. ...

Tips for designing a horizontal sub-navigation menu using CSS?

I have limited experience with list menus and am struggling to create a horizontal submenu with its own styling. Despite multiple attempts, I have been unsuccessful in finding a solution and have put the project on hold for now. Here is what I currently h ...

chosen=chosen based on data from mysql database

Currently, I'm developing my own CMS that allows users to add and update their projects. While the adding function works smoothly, the updating process also functions properly. However, a problem arises when I click on a project (retrieving informatio ...

What is the best way to choose all initial elements within a single row using CSS?

Is it possible to target all the first elements in a single row? I know this is an unusual request, but I have a row that contains block elements. I want to apply CSS styling to each of the first elements. Here is the row: <ul class="slides"> &l ...

Error: React js app has crashed. Currently waiting for file changes before restarting

I recently began using nodemon and started working on a small sample project. However, when I try to launch the server using sudo npm run dev, I encounter the following error: [nodemon] app crashed - waiting for file changes before starting... The error ...

Can Angular Flex support multiple sticky columns at once?

I am trying to make the information columns in my angular material table stay sticky on the left side. I have attempted to use the "sticky" tag on each column, but it did not work as expected. <table mat-table [dataSource]="dataSource" matSort class= ...

Developing a dynamic horizontal bar chart in d3 using a multidimensional array or nested JSON dataset

I am in the process of creating a straightforward d3 bar chart () by utilizing this specific nested json file. { "clustername": "cluster1", "children": [ { "neighborhoodname": "Shaw", "children": [ { "totpop2000": "1005", "children": [ ...

Discovering the process of extracting a date from the Date Picker component and displaying it in a table using Material-UI in ReactJS

I am using the Date Picker component from Material-UI for React JS to display selected dates in a table. However, I am encountering an error when trying to show the date object in a table row. Can anyone provide guidance on how to achieve this? import ...