Designing a versatile DIV that sorts through components with the power of HTML, CSS, and JavaScript

I have been exploring a tutorial on W3 about filtering elements using JavaScript. Here is the link to the tutorial: W3 filter elements

After following the tutorial, I noticed that the implementation leaves white space on the right side of the elements when they overflow:

https://i.sstatic.net/8ZdoI.png

I am curious about how the code can be modified to eliminate the excess white space and make the elements flexible. The HTML/CSS/JS code can be found on the original website. Any guidance on this would be greatly appreciated as I am new to this area.

Edit: An attempt was made to fix the CSS aspect of the issue, but it only worked for "Show All." When other categories are selected, unwanted elements still occupy space despite disappearing. I believe the solution lies in adjusting the JavaScript part of this section. https://i.sstatic.net/9UQu7.png

filterSelection("all")
function filterSelection(c) {
  var x, i;
  x = document.getElementsByClassName("filterDiv");
  if (c == "all") c = "";
  // Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
  for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");
    if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
  }
}

// Show filtered elements
function w3AddClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for (i = 0; i < arr2.length; i++) {
    if (arr1.indexOf(arr2[i]) == -1) {
      element.className += " " + arr2[i];
    }
  }
}

// Hide elements that are not selected
function w3RemoveClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for (i = 0; i < arr2.length; i++) {
    while (arr1.indexOf(arr2[i]) > -1) {
      arr1.splice(arr1.indexOf(arr2[i]), 1);
    }
  }
  element.className = arr1.join(" ");
}

// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
.container {
  overflow: hidden;
}

.filterDiv {
  float: left;
  background-color: #2196F3;
  color: #ffffff;
  width: 100px;
  line-height: 100px;
  text-align: center;
  margin: 2px;
  display: none; /* Hidden by default */
}

/* The "show" class is added to the filtered elements */
.show {
  display: block;
}

/* Style the buttons */
.btn {
  border: none;
  outline: none;
  padding: 12px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
}

/* Add a light grey background on mouse-over */
.btn:hover {
  background-color: #ddd;
}

/* Add a dark background to the active button */
.btn.active {
  background-color: #666;
  color: white;
}
<!-- Control buttons -->
<div id="myBtnContainer">
  <button class="btn active" onclick="filterSelection('all')"> Show all</button>
  <button class="btn" onclick="filterSelection('cars')"> Cars</button>
  <button class="btn" onclick="filterSelection('animals')"> Animals</button>
  <button class="btn" onclick="filterSelection('fruits')"> Fruits</button>
  <button class="btn" onclick="filterSelection('colors')"> Colors</button>
</div>

<!-- The filterable elements. Note that some have multiple class names (this can be used if they belong to multiple categories) -->
<div class="container">
  <div class="filterDiv cars">BMW</div>
  <div class="filterDiv colors fruits">Orange</div>
  <div class="filterDiv cars">Volvo</div>
  <div class="filterDiv colors">Red</div>
  <div class="filterDiv cars animals">Mustang</div>
  <div class="filterDiv colors">Blue</div>
  <div class="filterDiv animals">Cat</div>
  <div class="filterDiv animals">Dog</div>
  <div class="filterDiv fruits">Melon</div>
  <div class="filterDiv fruits animals">Kiwi</div>
  <div class="filterDiv fruits">Banana</div>
  <div class="filterDiv fruits">Lemon</div>
  <div class="filterDiv animals">Cow</div>
</div>

Answer №1

After some investigation, I was able to identify the issue at hand. It turns out that in my HTML code, the class "filterDiv" was only applied to the div wrapping the image src. Unfortunately, this did not account for the outer 'div' and 'a' elements, causing them to occupy unnecessary space. To rectify this, I made adjustments to the HTML structure as shown below:

<div class="filterDiv classic 2010 hiphop">
    <a href="https://soundcloud.com/tfrye/sets/friday-night-lights" id="fnl-jcole" target="_blank">
        <img src="https://images-na.ssl-images-amazon.com/images/I/51LMdp1N8bL._SL1000_.jpg" title="Friday Night Lights • J. Cole" class="fit-box" alt="Friday Night Lights by J. Cole Album Cover">
    </a>
</div>

Now, with filterDiv correctly applied to the exterior div, the layout functions as intended.

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

An assortment of the most similar values from a pair of arrays

I am seeking an algorithm optimization for solving a specific problem that may be challenging to explain. My focus is not on speed or performance, but rather on simplicity and readability of the code. I wonder if someone has a more elegant solution than mi ...

Utilizing CSS styling in PHP as a functional approach

In my journey of learning CSS, HTML5, and jQuery, I have found a unique way to organize my CSS code into different chapters. I simply call them into the head section when needed. This method allows me to have only the necessary CSS on each page, making it ...

Loop through two sets of data and perform multiplication on specific attributes when they match

I have a unique item that looks like this Object {SD00002:1,SD00011:3,SD00002:6} The values of the properties are set automatically. Currently, I have an array of similar objects as shown in the image below: https://i.sstatic.net/pSkvf.jpg My goal is to ...

Insert information into an array within a mongoDB structure using the Mongoose library

Is it possible to add elements into an array in a mongoDB schema? For instance, in the given schema: var ProviderSchema = new Schema({ keyWords: [String] }); How can I insert data into the keyWords field using the specified route: app.put(&a ...

Tips for saving the visibility status of a <div> in your browser bookmarks?

Currently, I am in the process of developing a single webpage (index.html). The navigation bar at the top includes links to hash references (DIV IDs). If JavaScript is enabled, clicking on these links triggers a JavaScript function with the onclick attribu ...

What is causing my Three.js scene to appear pitch black?

I am embarking on my first three.js project, but unfortunately my scene is appearing entirely black. I am utilizing Vite as my local server. Below is the JavaScript code I am currently using: import * as THREE from 'three' //Scene const scene = ...

What is the proper way to execute a script and transmit arguments when the client is connected via a socket?

Is it possible to execute a script that passes arguments to a connected client using Socket.IO? Here's an example scenario: var io = require('socket.io').listen(http); io.sockets.on('connection', function (client) { console ...

Maintaining the integrity of Jquery Tab even after refreshing the page is essential

I recently started using Jquery and encountered an issue with tab implementation. Whenever I refresh the page, it automatically directs me back to the initial tab setting. $(function() { var indicator = $('#indicator'), i ...

Error: The ORM class object cannot be converted to a string. <img src>

Hey there, I'm still quite new to PHP and idorm so bear with me. I've spent a lot of time searching for a solution to this particular issue without luck. The error message "Object of class ORM could not be converted to string" keeps popping up i ...

Having trouble with Ionic 4 navigation not triggering after a single click, requiring multiple clicks to navigate

I have a long list of items, around 40 in total, that load a page describing each item with photos, URLs, and other content. However, I find that I need to click two to three times before reaching this page. I suspect that the excessive use of HTML compone ...

What is the most effective way to configure a database for a project that will be utilized across multiple sub-domains, and what is the optimal

Embarking on the development of a large-scale web project meant to be utilized across multiple sub-domains representing different clients has me feeling lost. I am struggling to determine the best or most recommended solution for this type of undertaking. ...

Developing a form using ASP.NET with dual models

I am currently using Visual Studio 2017 with all the latest updates installed. I am facing a challenge where I need to create a form with text box answer questions and a checkbox answer question, and then store all the answers in a single database entry. M ...

Adding the active class in Bootstrap can be easily achieved in CodeIgniter by using the

I am seeking guidance on how to add an active class in CodeIgniter when dividing the view into three separate files. These files include: header.php page1.php ... page10.php footer.php According to this thread, there seems to be no clear solution prov ...

What is the best way to adjust the priority of elements using JavaScript in an ASP.NET MVC application?

As part of my application, I need to create a function that allows for the changing of deputy priorities for each consultant. Here is what I have implemented so far: View: @model ML.Domain.DAL.DB_CONSULTANTS .... <table> <tr> < ...

Issue in TypeScript: Property '0' is not found in the type

I have the following interface set up: export interface Details { Name: [{ First: string; Last: string; }]; } Within my code, I am using an observable configuration variable: Configuration: KnockoutObservable<Details> = ko.observable& ...

Modifying the font style of a Flot bar chart

Issue I am facing a challenge with adjusting the small numbers displayed on top of a bar chart created using Flot. It seems like these numbers are generated through canvas, making it difficult for me to customize them to match the styles I have set for th ...

Looking for a Handlebars helper that can determine if a value is greater than 1 or less than 2, and then render specific code based on which condition is satisfied

My login route is saving user data with a permission_id key that needs to be checked to determine whether it is greater than 1 or less than 2. Depending on the value of permission_id, I need to render different HTML content to allow or restrict access to c ...

Why did the creators choose to integrate a dropdown menu into Twitter Bootstrap?

While exploring Twitter's Bootstrap framework, I couldn't help but be impressed. However, one feature that has left me a bit puzzled is the dropdown navigation menu. First of all, to view child links, you need to click on the parent. I understan ...

Displaying a dynamic flag icon in a span element based on the selection from a mat-select

I am working on a mat-select component and I want to dynamically change a flag icon inside a span element in the mat-label based on the selected option. Currently, the initial flag is displayed correctly, but when I click on a different option, the flag d ...

Aligning two lines next to a radio button using HTML and CSS

I'm facing a challenge where I want to align two lines in the middle of a radio button. Despite my efforts, I am able to line up the top line but struggling with the bottom one. I prefer not floating the radio button as it's being styled using a ...