Home > Blockchain >  Add multiple filtering keywords to a single blog in a gallery?
Add multiple filtering keywords to a single blog in a gallery?

Time:01-03

I am planning to add a filtering feature to my website blogs. For this, each blog post will be associated with a keyword. Selecting these keywords will show/filter all the blogs associated with that specific keyword category.

In the code below, I have separated my blogs into 3 categories (Forest, Birds and Sea). However, I also want some of the blogs to be associated with multiple keywords (two or three), see the 'Forest Birds' section in the snippet below. If someone can help me with how to do it, that would be great.

Codes can be referred to here as well: https://jsfiddle.net/chandrakant98c/e5u08d1q/1/#&togetherjs=l4Kte0VJDV

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <style>
    /* Wildcard styling */
    
    * {
      box-sizing: border-box;
    }
    /* Padding for whole body */
    
    body {
      padding: 1px;
    }
    
    .container {
      max-width: 1200px;
      margin: auto;
    }
    /* Styling h2 tag */
    
    h1 {
      Color: green;
      word-break: break-all;
    }
    /* Anchor tag decoration */
    
    a {
      text-decoration: none;
      color: #5673C8;
    }
    
    a:hover {
      color: lightblue;
    }
    
    .row {
      margin: 0px -14px;
      padding: 8px;
    }
    
    .row>.column {
      padding: 6px;
    }
    
    .column {
      float: left;
      width: 33%;
      display: none;
    }
    /* Content decoration */
    
    .content {
      background-color: white;
      padding: 10px;
      border: 1px solid gray;
    }
    /* Paragraph decoration */
    
    p {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 40;
      overflow: hidden;
    }
    
    .row:after {
      content: "";
      display: table;
      clear: both;
    }
    
    .content {
      background-color: white;
      padding: 10px;
      border: 1px solid gray;
    }
    
    .show {
      display: block;
    }
    /* Style the filter buttons */
    
    .bttn {
      border: none;
      padding: 8px 14px;
      background-color: gray;
    }
    
    .bttn:hover {
      background-color: #007EE5;
      opacity: 0.8;
    }
    
    .bttn.active {
      background-color: #007EE5;
      color: white;
    }
    /* Window size 850 width set */
    
    @media screen and (max-width: 850px) {
      .column {
        width: 50%;
      }
    }
    /* Window size 400 width set */
    
    @media screen and (max-width: 400px) {
      .column {
        width: 100%;
      }
    }
  </style>
</head>

<body>

  <!-- Title and tag -->
  <div >

    <!-- button foreach group -->
    <div id="filtering">
      <button  onclick="geeksportal('all')">
            Show all
            </button>

      <button  onclick="geeksportal('Forest')">
            Forest
            </button>

      <button  onclick="geeksportal('Sea')">
            Sea
            </button>

      <button  onclick="geeksportal('Birds')">
            Birds
            </button>
    </div>

    <!-- Portfolio Gallery Grid -->
    <div >
      <div >
        <div >
          <img src="https://learnenglishteens.britishcouncil.org/sites/teens/files/styles/article/public/field/image/rs930_135120665-low.jpg?itok=g5LI5W4C" alt="HTML" style="width:100%">
          <h3><a href="#">
                        Forest Wiki
                        </a>
          </h3>

          <p>
            A forest is an area of land dominated by trees.[1] Hundreds of definitions of forest are used throughout the world, incorporating factors such as tree density, tree height, land use, legal standing, and ecological function.[2][3][4] The United Nations'
            Food and Agriculture Organization (FAO) defines a forest as, "Land spanning more than 0.5 hectares with trees higher than 5 meters and a canopy cover of more than 10 percent, or trees able to reach these thresholds in situ. It does not include
            land that is predominantly under agricultural or urban use."[5] Using this definition, Global Forest Resources Assessment 2020 (FRA 2020) found that forests covered 4.06 billion hectares (10.0 billion acres; 40.6 million square kilometres;
            15.7 million square miles), or approximately 31 percent of the world's land area in 2020.
          </p>

        </div>
      </div>
      <div >
        <div >
          <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMcwhEBBzhEUHD29jjdZswug7yXgje_WtbXA&usqp=CAU" alt="CSS" style="width:100%">
          <h3><a href="#">
                        Birds Wiki
                        </a>
          </h3>

          <p>
            Birds are a group of warm-blooded vertebrates constituting the class Aves /ˈeɪviːz/, characterised by feathers, toothless beaked jaws, the laying of hard-shelled eggs, a high metabolic rate, a four-chambered heart, and a strong yet lightweight skeleton.
            Birds live worldwide and range in size from the 5.5 cm (2.2 in) bee hummingbird to the 2.8 m (9 ft 2 in) ostrich. There are about ten thousand living species, more than half of which are passerine, or "perching" birds. Birds have wings whose
            development varies according to species; the only known groups without wings are the extinct moa and elephant birds. Wings, which evolved from forelimbs, gave birds the ability to fly, although further evolution has led to the loss of flight
            in some birds, including ratites, penguins, and diverse endemic island species. The digestive and respiratory systems of birds are also uniquely adapted for flight. Some bird species of aquatic environments, particularly seabirds and some
            waterbirds, have further evolved for swimming.
          </p>

        </div>
      </div>
      <div >
        <div >
          <img src="https://climate.nasa.gov/system/news_items/main_images/2990_9827327865_98e0f0dc2d_o.jpg" alt="" style="width:100%">
          <h3><a href="#">
                        Sea Wiki
                        </a>
          </h3>

          <p>
            The sea, connected as the world ocean or simply the ocean, is the body of salty water that covers approximately 71 percent of the Earth's surface. The word sea is also used to denote second-order sections of the sea, such as the Mediterranean Sea, as
            well as certain large, entirely landlocked, saltwater lakes, such as the Caspian Sea.
          </p>

        </div>
      </div>
      <div >
        <div >
          <img src="https://c4.wallpaperflare.com/wallpaper/73/551/750/spring-rendezvous-forest-bird-green-wallpaper-preview.jpg" alt="" style="width:100%">
          <h3><a href="#">
                        Forest Birds
                        </a>
          </h3>

          <p>
            Types of forest birds are those that will be seen more often than not in tree lots and forested areas. When these bird species decide to travel in their spring or fall migrations, it is usually non-stop over open expanses until they can seek the cover
            of woodlots or larger forests, where they are the most comfortable with their surroundings. Once these different types of birds settle in their habitat, some will be found on the forest floor, others will be in the newer growths that are not
            high and again others will live in the higher areas of the trees right up into the canopies of the treetops. These birds will be a combination of seed eaters and insect eaters. As insect eaters, they manage the insect population and help the
            trees, by reducing the amount of insect damage being done to them. The seed-eating birds, as an example, the crossbills help the forest by opening the cones and letting seeds fall to the ground thereby giving them the opportunity to germinate
            in the soil and grow into young trees.


          </p>

        </div>
      </div>
    </div>
  </div>

  <script>
    geeksportal("all")

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

    // Add active class to the current
    // button (highlight it)
    var btnContainer = document.getElementById("filtering");
    var btns = btnContainer.getElementsByClassName("bttn");
    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";
      });
    }
  </script>
</body>

</html>

CodePudding user response:

Here's what you can change, on line 198:

<div >

You're ordering "Forest Birds" as "Birds" only. Changing line 198 to this should fix it:

<div >
            

CodePudding user response:

I would strongly discourage you to use className to change class names like that, I would instead use classList in this case.

As to your initial question on how to do add an image that would have say both birds in a forest using both the bird button and forest button, this can be accomplished by adding the class of both bird and forest to images that would have both birds and forest scenery --> <div >. Then for example when you check your column nodelist with your conditional, if the column class list contains -> columns.classList.contains('birds') then add the class show --> columns.classList.add('show') it will show that column.

You really do not need all those convoluted functions and code though. I suggest add a JS eventHandler rather than onclick events in your HTML. This will allow you to run all the code through a single function and handle the event directly. A couple of conditionals to handle the buttons active and columns show is all that is needed.

Take a look at the refactored code below, I have added detailed comments within the code snippit to further assist in the explanation.

If you have questions about anything in particular let me know.

NOTE: on conditionals... I have used ternary conditionals in the explanation, these are the same as a regular conditional they are simply short hand versions.

col.classList.contains(btnId) ? col.classList.add('show') : null 

is the same as

if(col.classList.contains(btnId)){
  col.classList.add('show')
}else{
  null
}

// intial query of the codument to get the buttons by their class selector
const button = document.querySelectorAll('.bttn');

// call back function to be used in the event handler within the 
// forEach function on the buttons node list we pass the event "e"
function showSections(e){

  // define a variable for the event.target.dataset.id set in the buttons html
  let btnId = e.target.dataset.id;
  
  // define a varaible for the column nodeList array
  let columns = document.querySelectorAll('.column');
  
  // run over the buttons nodeList and check/set the active class
  // we are using classList and NOT className, researching the difference 
  // of the two will be good on your end...
  button.forEach(btn => {
    // rather than checking each class, lets just remove active class then check
    btn.classList.remove('active');
    // conditional check if btn.dataset is the button pressed
    // if so, add the active class using btn.classList.add('active')
    btn.dataset.id === btnId ? btn.classList.add('active') : null
  })
  
  // run over the column nodeLists and check/set the show class
  // again we are using classList and NOT className...
  columns.forEach(col => {
    // again remove all iterations of show class
    col.classList.remove('show');
    // now check if the columns classList contains the dataset id 
    // from the button using e.target.dataset.id 
    col.classList.contains(btnId) ? col.classList.add('show') : null  
    btnId === 'all' ? col.classList.add('show') : null
  })
}

// forEach looping over the button node list
button.forEach(btn => {
  btn.addEventListener('click', showSections)
})
/* Wildcard styling */

* {
  box-sizing: border-box;
}


/* Padding for whole body */

body {
  padding: 1px;
}

.container {
  max-width: 1200px;
  margin: auto;
}


/* Styling h2 tag */

h1 {
  Color: green;
  word-break: break-all;
}


/* Anchor tag decoration */

a {
  text-decoration: none;
  color: #5673C8;
}

a:hover {
  color: lightblue;
}

.row {
  margin: 0px -14px;
  padding: 8px;
}

.row>.column {
  padding: 6px;
}

.column {
  float: left;
  width: 33%;
  display: none;
}


/* Content decoration */

.content {
  background-color: white;
  padding: 10px;
  border: 1px solid gray;
}


/* Paragraph decoration */

p {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 40;
  overflow: hidden;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

.content {
  background-color: white;
  padding: 10px;
  border: 1px solid gray;
}

.show {
  display: block;
}


/* Style the filter buttons */

.bttn {
  border: none;
  padding: 8px 14px;
  background-color: gray;
}

.bttn:hover {
  background-color: #007EE5;
  opacity: 0.8;
}

.bttn.active {
  background-color: #007EE5;
  color: white;
}


/* Window size 850 width set */

@media screen and (max-width: 850px) {
  .column {
    width: 50%;
  }
}


/* Window size 400 width set */

@media screen and (max-width: 400px) {
  .column {
    width: 100%;
  }
}
<!-- Title and tag -->
<div >

  <!-- button foreach group -->
  <div id="filtering">
  <!-- CHANGED - removed onclick attributes and added active class states 
       to the buttons directly, changes will be handled by JS event handlers
       within javascript functionand not in onlick attributes in HTML 
       Also added dataset id's for handling conditionals to change 
       like images -->
    <button data-id="all" >Show all</button>

    <button data-id="forest" >Forest</button>

    <button data-id="sea" >Sea</button>

    <button data-id="birds" >Birds</button>
  </div>

  <!-- Portfolio Gallery Grid -->
  <div >
    <!-- CHANGED  Added classes the reflect the types of content contined with in 
    this column. for example this column has only forest, also changed the classes to
    lower clse to match the dataset id from the corresponding button  and added the 
    show class for initializing the first iteration of DOM loading -->
    <div >
      <div >
        <img src="https://learnenglishteens.britishcouncil.org/sites/teens/files/styles/article/public/field/image/rs930_135120665-low.jpg?itok=g5LI5W4C" alt="HTML" style="width:100%">
        <h3>
          <a href="#">Forest Wiki</a>
        </h3>
        <p>A forest is an area of land dominated by trees.[1] Hundreds of definitions of forest are used throughout the world, incorporating factors such as tree density, tree height, land use, legal standing, and ecological function.[2][3][4] The United Nations' Food and Agriculture Organization (FAO) defines a forest as, "Land spanning more than 0.5 hectares with trees higher than 5 meters and a canopy cover of more than 10 percent, or trees able to reach these thresholds in situ. It does not include land that is predominantly under agricultural or urban use."[5] Using this definition, Global Forest Resources Assessment 2020 (FRA 2020) found that forests covered 4.06 billion hectares (10.0 billion acres; 40.6 million square kilometres; 15.7 million square miles), or approximately 31 percent of the world's land area in 2020.</p>
      </div>
    </div>
    <!-- CHANGED  Added classes the reflect the types of content contined with in 
    this column. For example this column has only birds, also changed the classes to
    lower case to match the dataset id from the corresponding button and added the 
    show class for initializing the first iteration of DOM loading -->
    <div >
      <div >
        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMcwhEBBzhEUHD29jjdZswug7yXgje_WtbXA&usqp=CAU" alt="CSS" style="width:100%">
        <h3>
          <a href="#">Birds Wiki</a>
        </h3>
        <p>Birds are a group of warm-blooded vertebrates constituting the class Aves /ˈeɪviːz/, characterised by feathers, toothless beaked jaws, the laying of hard-shelled eggs, a high metabolic rate, a four-chambered heart, and a strong yet lightweight skeleton. Birds live worldwide and range in size from the 5.5 cm (2.2 in) bee hummingbird to the 2.8 m (9 ft 2 in) ostrich. There are about ten thousand living species, more than half of which are passerine, or "perching" birds. Birds have wings whose development varies according to species; the only known groups without wings are the extinct moa and elephant birds. Wings, which evolved from forelimbs, gave birds the ability to fly, although further evolution has led to the loss of flight in some birds, including ratites, penguins, and diverse endemic island species. The digestive and respiratory systems of birds are also uniquely adapted for flight. Some bird species of aquatic environments, particularly seabirds and some waterbirds, have further evolved for swimming.</p>
      </div>
    </div>
    <!-- CHANGED  Added classes the reflect the types of content contined with in 
    this column. For example this column has only sea, also changed the classes to
    lower case to match the dataset id from the corresponding button and added the 
    show class for initializing the first iteration of DOM loading -->
    <div >
      <div >
        <img src="https://climate.nasa.gov/system/news_items/main_images/2990_9827327865_98e0f0dc2d_o.jpg" alt="" style="width:100%">
        <h3>
          <a href="#">Sea Wiki</a>
        </h3>
        <p>The sea, connected as the world ocean or simply the ocean, is the body of salty water that covers approximately 71 percent of the Earth's surface. The word sea is also used to denote second-order sections of the sea, such as the Mediterranean Sea, as well as certain large, entirely landlocked, saltwater lakes, such as the Caspian Sea.</p>
      </div>
    </div>
    <!-- CHANGED * Added classes the reflect the types of content contined with in 
    this column. For example this column has both birds and forest, also changed the 
    classes to lower case to match the dataset id from the corresponding button and 
    added the show class for initializing the first iteration of DOM loading -->
    <div >
      <div >
        <img src="https://c4.wallpaperflare.com/wallpaper/73/551/750/spring-rendezvous-forest-bird-green-wallpaper-preview.jpg" alt="" style="width:100%">
        <h3>
          <a href="#">Forest Birds</a>
        </h3>
        <p>Types of forest birds are those that will be seen more often than not in tree lots and forested areas. When these bird species decide to travel in their spring or fall migrations, it is usually non-stop over open expanses until they can seek the cover of woodlots or larger forests, where they are the most comfortable with their surroundings. Once these different types of birds settle in their habitat, some will be found on the forest floor, others will be in the newer growths that are not high and again others will live in the higher areas of the trees right up into the canopies of the treetops. These birds will be a combination of seed eaters and insect eaters. As insect eaters, they manage the insect population and help the trees, by reducing the amount of insect damage being done to them. The seed-eating birds, as an example, the crossbills help the forest by opening the cones and letting seeds fall to the ground thereby giving them the opportunity to germinate in the soil and grow into young trees.</p>
      </div>
    </div>
  </div>
</div>

  • Related