Steps for organizing a list based on the number of clicks

I've created an HTML list with images of political party logos. Each logo is a grid item that can be clicked on. I want to sort the list based on the number of clicks each logo receives, essentially ranking them by popularity. However, I'm not sure how to write the JavaScript code to accomplish this task as I have limited experience with JavaScript.

If anyone has expertise in JavaScript and can provide guidance or assistance in creating the sorting functionality, it would be greatly appreciated. I've attempted a few approaches myself, but so far none have been successful.

Answer №1

Want to organize a list using CSS? Here's how you can do it 🤣 :

function adjustOrder(event) {
  let li = event.target.closest('.order-me')
  if (li) li.style.order -= 1;
}
document.querySelector('.grid-container').onclick = adjustOrder
.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  align-self: center;
  justify-self: center;
  margin: auto;
}

.grid-item {
  align-self: center;
  justify-self: center;
  text-align: center;
}

.grid-item::after{
  content: 'style="' attr(style) '"';
  display: block;
}
<ul class="grid-container" onclick="adjustOrder">
    <li class="grid-item order-me">50plus</li>
    <li class="grid-item order-me">bbb </li>
    <li class="grid-item order-me">bvnl</li>
    <li class="grid-item order-me">cda</li>
    <li class="grid-item order-me">PVV</li>
    <li class="grid-item order-me">christenunie</li>
    <li class="grid-item order-me">D66</li>
    <li class="grid-item order-me">Denk</li>
    <li class="grid-item order-me">FVD</li>
    <li class="grid-item order-me">JA21</li>
    <li class="grid-item order-me">NSC</li>
    <li class="grid-item order-me">PVDAGROENLINKS</li>
    <li class="grid-item order-me">PVDD</li>
    <li class="grid-item order-me">SGP</li>
    <li class="grid-item order-me">SP</li>
    <li class="grid-item order-me">Volt</li>
    <li class="grid-item order-me">VVD</li>
</ul>

Answer №2

As pointed out by @Barmer;, one way to achieve your goal is by utilizing the data-clicks attribute. I have made some adjustments to your code. Here's an example:

const listItems = document.querySelectorAll('.grid-item');
const list = document.getElementById('Partijensort');

list.addEventListener('click', function(e) {
    if (e.target.classList.contains('grid-item')) {
        let clicks = event.target.getAttribute('data-clicks') || 0;
        event.target.setAttribute('data-clicks', ++clicks);
        sortListItems();
    }
});

function sortListItems() {
  const listItemsArr = Array.from(listItems);
  listItemsArr.sort(function(a, b) {
    const clicksA = a.getAttribute('data-clicks') || 0;
    const clicksB = b.getAttribute('data-clicks') || 0;
    return clicksB - clicksA;
  });
  listItemsArr.forEach(function(listItem) {
    list.appendChild(listItem);
  });
}
.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  align-self: center;
  justify-self: center;
  width: 80vw;
  margin: auto;
}

.grid-item {
  align-self: center;
  justify-self: center;
  font-size: 1em;
  text-align: center;
  height: 10vw;
  width: 10vw;
  margin-top: 1vw;
  filter: drop-shadow(10px 10px 10px rgba(0, 0, 0, 0.25));
}
<ul id="Partijensort" class="grid-container">
  <li data-clicks="0" class="grid-item" id="plus">50plus</li>
  <li data-clicks="0" class="grid-item" id="bbb">bbb </li>
  <li data-clicks="0" class="grid-item" id="bvnl">bvnl</li>
  <li data-clicks="0" class="grid-item" id="cda">cda</li>
  <li data-clicks="0" class="grid-item" id="pvv">PVV</li>
</ul>

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

Incorporating a closing screen into a game built with Canvas and jQuery

After following a tutorial on creating a snake game, I decided to work on enhancing it as a side project. Currently, the game has a start screen where players can begin the game by pressing "start." My goal is to implement an end screen that displays the ...

Guide on submitting a form using a custom AJAX function based on the id or class parameter

Instead of writing an ajax call every time with changing API URL, post method, and form id or class name based on the page, I am attempting to develop a custom function that can manage the API call based on the provided parameters. The essential parameters ...

Adding a text field on top of a div based on the dropdown value selection

I am working with a dropdown option inside a div. I want to make it so that when the last option is selected, a text box will appear on top of the dropdown. And when a different option is selected, the text box should be disabled. How can I achieve this? ...

What is the best way to display all divs once more after all filter-checkboxes have been unchecked?

I created a custom filter that displays board games based on the number of players and playing time selected through checkboxes. Initially, the filter works as intended when first loaded and used. However, I encountered an issue where if all checkboxes are ...

After updating the INNERHTML, the NAV tag content is no longer functional

I am facing an issue with replacing the contents of a NAV tag that contains UL list items. The original HTML within the NAV tag works perfectly fine, but when I replace it with my own HTML - which matches the original word for word - the dropdown functiona ...

Altering the input type of a cloned element in Internet Explorer results in the loss of the value

When I have checkbox inputs displayed in a modal with preset value attributes, upon clicking "OK", I clone them and change their input types to hidden, then append them to a div in the document body. However, when trying to retrieve their values using jQue ...

Determining the height of a different element using only CSS, Stylus, or Nib

Looking to create a navigation bar using CSS Markup: <nav> Navigation content </nav> <div id="mainContent"> Main page content </div> CSS: nav { position:fixed; height: X%; min-height: Ypx; } #mainContent { ...

Unexpected response received from ajax call when supplying data to flot.js

Within this script block, I am retrieving data from a database in order to create a line graph. However, the data is returning as undefined and the graph is not being generated. var d; var arr = []; $(function() { var data; $.ajax({ da ...

Confirming delete with jQuery and AJAX

Before sending an AJAX request to remove an item from the database, I require an OK/Cancel delete confirmation dialog box. var id=ID; $.ajax({ type: "POST", url: "sample.aspx?Mode=Delete", data: { id: id }, success: function (response) ...

There is no record of the property's history

I am embarking on a fresh project utilizing React and TypeScript. One of the hurdles I have encountered is with the Router. Strangely, TypeScript does not recognize the history property, even though it should be accessible as mentioned in the documentation ...

Error: The module you are trying to import from the package is not found. Please check the package path and make sure that

I encountered an issue when trying to compile a code in Reactjs. As a beginner in Reactjs, I'm struggling with this. Module not found: Error: Package path ./cjs/react.development is not exported from package /Users/mansi/letsgrowmore/to-do-list/my-rea ...

What's preventing me from utilizing Leaflet Map on Next.js despite attempting Dynamic Import?

When using Leaflet, it requires the global window object which is not available on SSR (Server-Side Rendering) and can cause an error stating "window is not defined". I have tried extensively to find a solution, and the only method I found was to use dyna ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...

Response from Socket.io: What is the best way for the server to respond to all clients after receiving input from multiple clients?

Currently diving into the realm of node.js, express, and socket.io Thrilled to report that my server is up and running, successfully connecting to the browser via localhost:3000 Communication between client and server is seamless both ways. Now, onto th ...

I'm having an issue with my Bootstrap tabs - they seem to be unresponsive when clicked

I've been working on a Bootstrap website and have run into some issues that I can't seem to resolve. One problem I encountered was with a set of tabs that were supposed to be interactive, but for some reason, they weren't working as expected ...

I encountered a "Bad Request" error when trying to login through my nodejs server, and I'm unsure of the reason behind this issue. As a beginner in nodejs, I'm still learning the ins and

passport.use(new LocalStrategy(async(email,password,done) => {    try{     const user = await User.findOne({email:email})     if(!user){        return done(null,false,{message:"Invalid email"})     }     const isValidPassword =aw ...

retrieve the list of css stylesheets connected to a webpage

Currently, I am running some tests on Firefox's Error Console. My main focus is on identifying and rectifying errors in the stylesheets. For regression testing purposes, I need to compile a list of all HTML pages that are connected to these stylesheet ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

Ensuring continuity of session in WebRTC audio calls post page refresh

Currently, I am utilizing the Kandy WebRTC library to facilitate audio calls through WebRTC. One issue I have encountered is maintaining the session alive if a user refreshes the page, as this JavaScript library operates internally using WebSocket. For in ...

Django static files reference

sample code snippet tooltip reference navigating to the correct file path FILES: settings.py STATICFILES_DIRS = [ BASE_DIR / "static" , ] base.html {% load static %} How can I properly link my static files in the html line below?... &l ...