Image Filter: Only Display Selected Images, Not All

I have designed a Filter Image Gallery where all images are initially displayed when the page loads. There are four different tabs available - Show all, Nature, Cars, and People.

However, I want to change this default behavior so that only Nature filter images are shown by default after the page is loaded.

If you would like to review my code, you can find it here: CodePen Link

You can also view my code snippet below:

   filterSelection("all")
    function filterSelection(c) {
      var x, i;
      x = document.getElementsByClassName("column");
      if (c == "all") c = "";
      for (i = 0; i < x.length; i++) {
        w3RemoveClass(x[i], "show");
        if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
      }
    }
    
    // Additional JavaScript functions...

Please note that changing the default display to show only Nature images has been challenging as all images continue to display. Thank you in advance for your help.

Answer №1

update this line in js file:

filterSelection("all")

to

filterSelection("nature")

and switch from the "all" radio option being checked to the "nature" radio option being checked

filterSelection("nature")
    function filterSelection(c) {
      var x, i;
      x = document.getElementsByClassName("column");
      if (c == "all") c = "";
      for (i = 0; i < x.length; i++) {
        w3RemoveClass(x[i], "show");
        if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
      }
    }
    
    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];}
      }
    }
    
    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(" ");
    }
* {
    box-sizing: border-box;
}

body {
    background-color: #f1f1f1;
    padding: 20px;
    font-family: Arial;
}

/* Center website */
.main {
    max-width: 1000px;
    margin: auto;
}

h1 {
    font-size: 50px;
    word-break: break-all;
}

.row {
    margin: 10px -16px;
}

/* Add padding BETWEEN each column */
.row,
.row > .column {
    padding: 8px;
}

/* Create three equal columns that floats next to each other */
.column {
    float: left;
    width: 33.33%;
    display: none; /* Hide all elements by default */
}

/* Clear floats after rows */ 
.row:after {
    content: "";
    display: table;
    clear: both;
}

/* Content */
.content {
    background-color: white;
    padding: 10px;
}

/* The "show" class is added to the filtered elements */
.show {
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">

<h1>MYLOGO.COM</h1>
<hr>

<h2>PORTFOLIO</h2>
<input type="radio" onclick="filterSelection('all')" name="category"> Show all
<input type="radio" onclick="filterSelection('nature')" name="category" checked> Nature
<input type="radio" onclick="filterSelection('cars')" name="category"> Cars
<input type="radio" onclick="filterSelection('people')" name="category"> People

<div class="main">

<h1>MYLOGO.COM</h1>
<hr>

<h2>PORTFOLIO</h2>
<input type="radio" onclick="filterSelection('all')" name="category" > Show all
<input type="radio" onclick="filterSelection('nature')" name="category" checked> Nature
<input type="radio" onclick="filterSelection('cars')" name="category"> Cars
<input type="radio" onclick="filterSelection('people')" name="category"> People

<!-- Portfolio Gallery Grid -->
<div class="row">
<div class="column nature">
<div class="content">
<img src="/w3images/mountains.jpg" alt="Mountains" style="width:100%">
<h4>Mountains</h4>
<p>Lorem ipsum dolor..</p>
</div>
</div>
<div class="column nature">
<div class="content">
<img src="/w3images/lights.jpg" alt="Lights" style="width:100%">
<h4>Lights</h4>
<p>Lorem ipsum dolor..</p>
</div>
</div>
<div class="column nature">
<div class="content">
<img src="/w3images/nature.jpg" alt="Nature" style="width:100%">
<h4>Forest</h4>
<p>Lorem ipsum dolor..</p>
</div>
</div>

<div class="column cars">
<div class="content">
<img src="/w3images/cars1.jpg" alt="Car" style="width:100%">
<h4>Retro</h4>
<p>Lorem ipsum dolor..</p>
</div>
</div>
<div class="column cars">
<div class="content">
<img src="/w3images/cars2.jpg" alt="Car" style="width:100%">
<h4>Fast</h4>
<p>Lorem ipsum dolor..</p>
</div>
</div>
<div class="column cars">
<div class="content">
<img src="/w3images/cars3.jpg" alt="Car" style="width:100%">
<h4>Classic</h4>
<p>Lorem ipsum dolor..</p>
</div>
</div>

<div class="column people">
<div class="content">
<img src="/w3images/people1.jpg" alt="Car" style="width:100%">
<h4>Girl</h4>
<p>Lorem ipsum dolor..</p>
</div>
</div>
<div class="column people">
<div class="content">
<img src="/w3images/people2.jpg" alt="Car" style="width:100%">
<h4>Man</h4>
<p>Lorem ipsum dolor..</p>
</div>
</div>
<div class="column people">
<div class="content">
<img src="/w3images/people3.jpg" alt="Car" style="width:100%">
<h4>Woman</h4>
<p>Lorem ipsum dolor..</p>
</div>
</div>
<!-- END GRID -->
</div>

<!-- END MAIN -->
</div>

Answer №2

Here is a solution that might work for you:

window.onload = function () {
 document.getElementById('outdoors').checked=true;
filterSelection('outdoors');
}

To view the modified code, please visit this link: https://codepen.io/someuser/pen/JKobSt. If your issue still persists, feel free to reach out.

Answer №3

You should utilize the window.onload function

function filterSelection(c) {
  var x, i;
  x = document.getElementsByClassName("column");
  if (c == "all") c = "";
  for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");
    if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
  }
}

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];}
  }
}

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(" ");
}

window.onload = function () {
 document.getElementById('nature').checked=true;
filterSelection('nature');
}
* {
    box-sizing: border-box;
}

body {
    background-color: #f1f1f1;
    padding: 20px;
    font-family: Arial;
}

/* Center website */
.main {
    max-width: 1000px;
    margin: auto;
}

h1 {
    font-size: 50px;
    word-break: break-all;
}

.row {
    margin: 10px -16px;
}

/* Add padding BETWEEN each column */
.row,
.row > .column {
    padding: 8px;
}

/* Create three equal columns that floats next to each other */
.column {
    float: left;
    width: 33.33%;
    display: none; /* Hide all elements by default */
}

/* Clear floats after rows */ 
.row:after {
    content: "";
    display: table;
    clear: both;
}

/* Content */
.content {
    background-color: white;
    padding: 10px;
}

/* The "show" class is added to the filtered elements */
.show {
  display: block;
}
<div class="main">

<h1>MYLOGO.COM</h1>
<hr>

<h2>PORTFOLIO</h2>
<input type="radio" onclick="filterSelection('all')" name="category" checked> Show all
<input type="radio" id="nature" onclick="filterSelection('nature')" name="category"> Nature
<input type="radio" onclick="filterSelection('cars')" name="category"> Cars
<input type="radio" onclick="filterSelection('people')" name="category"> People

<!-- Portfolio Gallery Grid -->
<div class="row">
  <div class="column nature">
    <div class="content">
      <img src="/w3images/mountains.jpg" alt="Mountains" style="width:100%">
      <h4>Mountains</h4>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>
  <div class="column nature">
    <div class="content">
    <img src="/w3images/lights.jpg" alt="Lights" style="width:100%">
      <h4>Lights</h4>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>
  <div class="column nature">
    <div class="content">
    <img src="/w3images/nature.jpg" alt="Nature" style="width:100%">
      <h4>Forest</h4>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>
  
  <div class="column cars">
    <div class="content">
      <img src="/w3images/cars1.jpg" alt="Car" style="width:100%">
      <h4>Retro</h4>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>
  <div class="column cars">
    <div class="content">
    <img src="/w3images/cars2.jpg" alt="Car" style="width:100%">
      <h4>Fast</h4>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>
  <div class="column cars">
    <div class="content">
    <img src="/w3images/cars3.jpg" alt="Car" style="width:100%">
      <h4>Classic</h4>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>

  <div class="column people">
    <div class="content">
      <img src="/w3images/people1.jpg" alt="Car" style="width:100%">
      <h4>Girl</h4>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>
  <div class="column people">
    <div class="content">
    <img src="/w3images/people2.jpg" alt="Car" style="width:100%">
      <h4>Man</h4>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>
  <div class="column people">
    <div class="content">
    <img src="/w3images/people3.jpg" alt="Car" style="width:100%">
      <h4>Woman</h4>
      <p>Lorem ipsum dolor..</p>
    </div>
  </div>
<!-- END GRID -->
</div>

<!-- END MAIN -->
</div>

I trust this solution will meet your needs

Answer №4

One way to accomplish this is by assigning an id to the input element representing nature, and then triggering a click event on it when the window has finished loading.

<input type="radio" onclick="filterSelection('all')"  name="category" checked> Show all
<input type="radio" onclick="filterSelection('nature')" id="nature" name="category"> Nature
<input type="radio" onclick="filterSelection('cars')" name="category"> Cars
<input type="radio" onclick="filterSelection('people')" name="category"> People

window.onload = function(e){ 
    var naturalInput = document.getElementById('nature');
   naturalInput.click();
}

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

Surprising outcomes when hosting my website on its domain

During the development of my website, I uploaded it to Cpanel once everything was finished. It functioned perfectly fine at that time. However, after making some changes and uploading it again, the fonts and videos on the live domain appear larger than i ...

Simple method to retrieve unordered list identifiers as an array using PHP

Currently, I am working with an unordered list where I am using DB ids as the list-item ids. When the Submit button is pressed, I want to present all the ID's of my list items as an Array in PHP. I am still learning JavaScript and although there are s ...

Using Ajax in a separate JavaScript file

How can I retrieve data from an Ajax call made from a different .js file? Here is the code snippet I have been working with: function ajax(url, success, error) { success += "(data)"; error += "(xhr, ajaxOptions, thrownError)"; console.log("St ...

Interpreting Multilayered JSON Objects using JQuery

Hello everyone! I've posted my sample json data below. While I am proficient in PHP, I am relatively new to jQuery. "data":{ "cipher":"true", "size":[ "2.2 Mb", "6.11 Mb", "9.25 Mb", ...

sort through HTML table data following a selection from the dropdown menu

After selecting a dropdown entry from my SQL table, I can filter the results in my table accordingly. By default, the table displays results with status "finished" and "open". However, I am looking to have a static entry in the dropdown that shows me all r ...

What is the best way to incorporate inline css in Angular for various views that share identical content but require distinctive styles?

Below is my HTML code: <p ng-if= "editMode=='edit'" style="margin-left: 1px;margin-top: -2px;">===some messages---</p> <p ng-if= "editMode=='addNew'" style="margin-left: 1px;margin-top: -2px;">===some messages- ...

No content appears on the multi-form component in React

After several attempts at building a multi-step form in React, I initially created a convoluted version using React.Component with numerous condition tests to determine which form to display. Unsatisfied with this approach, I decided to refactor the code f ...

Trigger the UseEffect() function in a Material UI Dialog only when the dialog is open

In my project, I have a parent component that includes a Material UI Dialog as a child component. The purpose of this dialog is to fetch and display data from a REST API. Currently, I am using the UseEffect() function in the Dialog component to achieve th ...

"Discover the process of using Puppeteer to extract information from a website, even when dealing with input fields that are set

I'm attempting to replicate the structure of a website using puppeteer, and here's what I have so far: page = await this.createPage(browser); page.setContent(await originalPage.content()); The issue arises from input fields in the DOM that are ...

What is the best way to remove the class "active" from only one of the <li> elements using jQuery?

I am currently facing a challenge in figuring out how to remove the "active" class from just one of my lists. Here is an example of my navigation bar: <div class="container"> <ul class="nav"> <li class="active"><a href="#">& ...

Leverage HTML within JSON for a multilingual website using i18next with Next.js

I am working on a multi-language website using Next.js. To handle the translations, I am using the package i18next. In my JSX code, I define variables like this: {t("satisfied:title")} This means {t("JSONfileName:JSONvariable")} However, when I try to i ...

Techniques for simulating functions in Jest

I have a pair of basic components that I'm currently creating tests for using jest. My goal is to verify that when I click on a currencyItem, the corresponding array gets added to the select state. To achieve this, I am passing the handleCurrencyToggl ...

Personalize Badge Component

I've been on the hunt for a solution to customize a badge component similar to what's seen here: https://mui.com/material-ui/react-badge/. As of now, only options for making it a dot or adding a number in a circle are available. However, I' ...

Combining similar validators in VueJS into one group

Upon installation of the vuelidate.js.org package for VueJs, I implemented the following validator script: }), Validations: { name: { required, minLength: minLength(3), maxLength: maxLength(50) }, family: { required, minLength: ...

The hamburger menu appears to be missing when viewing in Safari, while it functions properly on both Chrome and Firefox browsers

My website has a responsive menu that functions perfectly in Chrome and Firefox, but encounters issues in Safari on mobile devices. The site is built using Elementor WordPress and I believe adding some -webkit- properties could solve the problem, but I&apo ...

Looking for recommendations on JSON format for an AJAX response?

Suppose I submit a form through Ajax and am awaiting a response from the server: Pass/fail status If fails, a compilation of validation errors including corresponding field ids/names, etc Is there a widely adopted or recommended JSON format for organizi ...

How do I retrieve the class of an element nested within another element using jQuery?

If we consider a scenario where there is a table named unitTables with various rows, each containing the selected class that we want to retrieve for a variable. This specific table is just one of many similar tables on the webpage. Since other tables also ...

XMLHttpRequest encounters issues with 'Access-Control-Allow-Origin'

I have developed a JavaScript file that tracks and saves the coordinates of mouse clicks on a web page using an AJAX call. In one website (domain2), I have included the following code in the head section: <script src="http://www.domain1.com/scan/track/ ...

Implementing a way to output a JavaScript script using PHP via AJAX

I need help with a JavaScript script that should be echoed when a certain condition is met. The issue arises when the file containing this script is called through Ajax by another page, as it fails to echo the <script>...</script> part. It seem ...

export default select an option

Forgive me if my question comes off as naive, but I'm still learning the ropes. :-) I stumbled upon something perplexing in this GitHub file. I am aware that we can export or import default functions, but in this instance, the author has used: expo ...