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

How can the vertical scroll bar position be reset in Material-Table when pagination is activated?

Whenever I scroll up or down in my Material-Table, and then switch pages, the vertical scroll bar doesn't reset to the top of the table. Instead, it stays where it was before changing the page, causing confusion for users. The only mention of scroll ...

Creating a personalized message for a failed "Get" request using the HTTPS native module in combination with

Currently, I have implemented an Express application that includes an HTTP GET request to an external API. It functions properly when there are no errors; however, I am looking to customize the response sent to the client-side in case of failures: const ht ...

Concealing anchor and span elements using CSS in Internet Explorer 7

I decided to simplify things by creating a style within the document to address my specific issue. The problem I encountered involves a row of 4 links that are designed to resemble buttons. I have chosen to hide the Next link (the 3rd item) using CSS. Whil ...

The properties of the NextFont variable cannot be utilized in the CSS global scope when using the var() function

// font.ts file import { Quicksand, Syncopate } from 'next/font/google'; export const quickSandRegular = Quicksand({ subsets: ['latin'], variable: '--font-quicksand-reg', weight: '400', display: 'swap& ...

Exploring the wonders of Node.js, Redis, and Express.js while navigating through the enchanting world of Asynchronous

Hello there, I must confess that this is a whole new realm for me... Here is what we've got: app.get('/user/:user_id/followings', function(req, res) { var response = {} , userId = req.params.user_id , ids = req.param(' ...

Three-column layout using CSS fluid design

The arrangement in Column B below does not look right. I successfully created a 3-column layout with the help of this resource. However, it assumes that fixed columns A and B have the same height or start at the same vertical position. In my case, B has an ...

I utilized the `<script src="sample.pdf"></script>` tag in my HTML code and surprisingly, the JavaScript within the PDF document was still able to execute

Recently, I encountered a situation where I included a PDF file with JavaScript code in the src attribute of a script tag in my code. Surprisingly, the JavaScript code executed without any issues. This made me wonder if I can use any type of file extension ...

enable jQuery timer to persist even after page refresh

code: <div class="readTiming"> <time>00:00:00</time><br/> </div> <input type="hidden" name="readTime" id="readTime"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script&g ...

Use jQuery to gather all the values from an HTML select element

I am using PHP to generate a HTML select option based on folders in a directory. Now, I am looking for a way to retrieve the value of the selected option in my jQuery script. I am familiar with $('#select :selected').text() and $(#select).val(), ...

Creating dynamic div containers on the fly

I'm dealing with an issue in my application where multiple overlapping div boxes are being dynamically generated and they all end up having the same content. When I add content to a box, it gets applied to all existing boxes instead of just the last o ...

How to decode JSON data into a JavaScript array and retrieve specific values using index positioning

Upon receiving a json response via ajax, the code looks like this: echo json_encode($data); The corresponding ajax code is shown below: $.ajax({ url:"PaymentSlip/check", data:{val:val}, type: 'POST', succe ...

Using Rails: How to invoke a function in the asset pipeline from a JS response?

In one of the JavaScript files I am working with, I have defined an object and a function: chosen.coffee Foo = do_this: -> $('.slider').slider() $ -> Foo.do_this() This code initializes JQueryUI to turn a specific div into a ...

Is there any method to determine whether a floated element has been pushed down?

Imagine a dynamic menu with floating elements, each set at a width of 150px. As the menu's width decreases, the elements progressively move to the next row. You are contemplating how to detect when an element has been moved down. One approach could b ...

Steps for designing image animations with fade in and fade out effects

I have a task to enhance the current code provided below, which currently works with only two images. HTML: <div id="cf"> <img class="bottom" src="<?php bloginfo('template_directory') ?>/assets/img/image1" /> <img class ...

Incorporating external content into your website: A guide

Currently, I am in the process of developing a website for personal use (without any intention of making profit). The vision for this website is to serve as a comprehensive "directory" featuring various posts sourced from different websites - similar to a ...

Eliminate billing information from the Woocommerce order management page on the backend

Is there a way to modify the text "Paid on" in the backend order details page of WooCommerce? I have already implemented this for BACS and local pickup payment methods. Replace a specific word for BACS payment method in Woocommerce order edit pages I am ...

Is there a point in bundling NPM packages if they are ultimately going to be bundled by the project

I'm in the process of creating a TypeScript package for publication on NPM. My plan is to utilize this package in upcoming web development endeavors, most likely utilizing Vite. As I look ahead to constructing a future website with this module, I am c ...

Comparing form submission with a button click to pass data using Ajax - success in one method but failure in the other

I am facing an issue with two pieces of jquery code in my Flask application. While one works perfectly, the other is not functioning as expected. Both the form and a button trigger the same function through ajax calls. Currently, for troubleshooting purpos ...

JQuery is failing to locate elements that have dynamic data titles assigned to them

I've been attempting to locate an element using a jQuery regex comparison in the data title. My situation involves having divs with the class .textbox, each containing a dynamically generated data title. To target specific boxes with that particular d ...

How can you customize gutter widths for specific rows in Bootstrap 3?

Currently, I am constructing my own website using Bootstrap 3 and have come across a challenge that I would like to address: My goal is to assign distinctive gutter widths to certain rows in my design. The remaining sections of the site will adhere to th ...