Filtering a webpage using JQuery by clicking to delete specific divs or sections

I have implemented a dropdown button at the top of my blog-style website to allow users to filter the content. Each blog post is contained within section tags.

When a user clicks on a menu item, it triggers a click event. I am trying to save the href, which the code seems to handle correctly.

My goal was to iterate through each a tag with the class of "label". For each one found, it should check the text and compare it to the value from the dropdown box. If it matches, keep the content. If not, detach it. I chose to use detach because I would need to reattach it on refresh or if the user selects another option in the dropdown.

This is what I attempted:

<div class="container blog-content">
  <div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" id="sortMenu" data-toggle="dropdown">Sort By:
     <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="sortMenu">
      <li role="presentation"><a role="sortmenuitem" id="Adventure">Adventure</a></li>
      <li role="presentation"><a role="sortmenuitem" id="Food">Food</a></li>
      <li role="presentation"><a role="sortmenuitem" id="Nature">Nature</a></li>
      <li role="presentation"><a role="sortmenuitem" id="Sites">Sites</a></li>
    </ul>
  </div>
    <div class="row">
    <div class="col-sm-12 blog-main">
      <div class="row">
        <div class="col-sm-6">
          <section class="blog-post">
            <div class="panel panel-default">
              <img src="myimage.jpg" class="img-responsive" />
              <div class="panel-body">
                <div class="blog-post-meta">
                  <span class="label label-light label-danger">Adventure</span>
                  <p class="blog-post-date pull-right">January 1, 2016</p>
                </div>
              <div class="blog-post-content">
                  <a href="post-image.html">
                    <h2 class="blog-post-title">Blog Title 1</h2>
                  </a>
                  <p>Lorem ipsum blah blah blah</p>
                  <a class="btn btn-info" href="post-image.html">Read more</a>
                  <a class="blog-post-share pull-right" href="#">
                    <i class="material-icons">&#xE80D;</i>
                  </a>
              </div>
            </div>
          </div>
          </section>
       <!-- /.blog-post -->
          <section class="blog-post">
            <div class="panel panel-default">
              <div class="panel-body">
                <div class="blog-post-meta">
                  <span class="label label-light label-info">Food</span>
                  <p class="blog-post-date pull-right">January 1, 2016</p>
                </div>
                <div class="blog-post-content">
                  <a href="post-image.html">
                    <h2 class="blog-post-title">Blog Title 2</h2>
                  </a>
                  <p>Lorem ipsum blah blah blah</p>
                  <a class="btn btn-info" href="post-image.html">Read more</a>
                  <a class="blog-post-share pull-right" href="#">
                    <i class="material-icons">&#xE80D;</i>
                  </a>
                </div>
              </div>
            </div>
          </section>
    <!-- /.blog-post -->

JQuery:

      <script>
        $("a[role='sortmenuitem']").bind("click", function() {
            var value = $(this).attr('id');
            $("a.label").each(function() {
              if (this.text('value')) {
                this.replace();
              }
              else {
                this.detach();
              }
            });
        });
    </script> 

If there is a better approach altogether, I am open to suggestions. I considered assigning each blog section a class that corresponds to its category and using CSS to hide the element. If this seems like the right direction, please let me know.

Additionally, once we hide the sections that do not match the selected dropdown menu item, I would need to show them again if another item is selected.

As I am new to JQuery, I would greatly appreciate any simplified explanations!

Answer №1

It seems like you are looking to toggle the visibility of blog posts based on the current dropdown selection.

In order to achieve this, you will need to make a slight modification. Replace this line:

$("a.label")

with:

$(".blog-post .label")

This change is necessary because the label is nested within the span element under the blog-post section.

When comparing a value with text, update the following line:

this.text('value')

to:

$(this).text()

To show/hide the section within the each loop, ensure that you target the nearest parent section which contains the blog post.

I've included e.preventDefault() inside the click function to prevent navigation.

Additionally, as mentioned in the comment (Khalid T), replace bind with on since bind is deprecated.

Here's the updated code snippet:

$("a[role='sortmenuitem']").on("click", function(e) {
  e.preventDefault();
  var value = $(this).attr( 'href' );
  $(".blog-post .label").each(function() {
    $(this).closest('.blog-post').toggle($(this).text() == value);
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<div class="container blog-content">
    <div class="dropdown">
        <button class="btn btn-default dropdown-toggle" type="button" id="sortMenu" data-toggle="dropdown">Sort By:
            <span class="caret"></span>
        </button>
        <ul class="dropdown-menu" role="menu" aria-labelledby="sortMenu">
            <li role="presentation"><a role="sortmenuitem" href="Adventure">Adventure</a></li>
            <li role="presentation"><a role="sortmenuitem" href="Food">Food</a></li>
            <li role="presentation"><a role="sortmenuitem" href="Nature">Nature</a></li>
            <li role="presentation"><a role="sortmenuitem" href="Sites">Sites</a></li>
        </ul>
    </div>
    <div class="row">
        <div class="col-sm-12 blog-main">
            <div class="row">
                <div class="col-sm-6">
                    <section class="blog-post">
                        <div class="panel panel-default">
                            <img src="myimage.jpg" class="img-responsive"/>

                            <div class="panel-body">
                                <div class="blog-post-meta">
                                    <span class="label label-light label-danger">Adventure</span>

                                    <p class="blog-post-date pull-right">January 1, 2016</p>
                                </div>
                                <div class="blog-post-content">
                                    <a href="post-image.html">
                                        <h2 class="blog-post-title">Blog Title 1</h2>
                                    </a>

                                    <p>Lorem ipsum blah blah blah</p>
                                    <a class="btn btn-info" href="post-image.html">Read more</a>
                                    <a class="blog-post-share pull-right" href="#">
                                        <i class="material-icons">&#xE80D;</i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </section>
                    <!-- /.blog-post -->
                    <section class="blog-post">
                        <div class="panel panel-default">
                            <div class="panel-body">
                                <div class="blog-post-meta">
                                    <span class="label label-light label-info">Food</span>

                                    <p class="blog-post-date pull-right">January 1, 2016</p>
                                </div>
                                <div class="blog-post-content">
                                    <a href="post-image.html">
                                        <h2 class="blog-post-title">Blog Title 2</h2>
                                    </a>

                                    <p>Lorem ipsum blah blah blah</p>
                                    <a class="btn btn-info" href="post-image.html">Read more</a>
                                    <a class="blog-post-share pull-right" href="#">
                                        <i class="material-icons">&#xE80D;</i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </div>
    </div>
</div>

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

Unacceptable response from AJAX function

My goal is to extract specific information from this ajax function, such as the thumbnail image and the owner of the image. It seems like the function is not recognizing data.images[i].imgurl and data.images[i].username. AJAX call in ajax.php require_o ...

When using Javascript to append content to the body, it may not be displayed as HTML on

My current project involves creating an HTML document through JavaScript templates. In the code snippet below, I have a const button which serves as my template. By using the replace method, I am able to update the content within the button template from c ...

Using JSTL within JavaScript

Can JavaScript be used with JSTL? I am attempting to set <c:set var="abc" value="yes"/> and then later retrieve this value in HTML and execute some code. The issue I'm facing is that the c:set always executes even when the JavaScript condition ...

Is there a way to align the content of the info window in Google Maps to the center

Check out this Stackblitz where I am facing an alignment problem with a Google Maps info window. Despite removing the close button, the window's positioning seems skewed due to padding and/or margins on the right side. I'm looking for ways to pr ...

Does the padding attribute get passed down in CSS?

Hi there! I've been working on the following code snippet: .blah { padding: 15px; background:green; } .blah div{ background:red; } <div class='blah'> <div> foo </div> & ...

Which specific web framework supports the functionalities of Microsoft Dynamics CRM 2011?

Is there an SDK available from Microsoft that can help me create a web product with similar rich ajax features as Microsoft Dynamics CRM 2011? I have considered using Microsoft SharePoint Foundation 2010, but I am concerned that it is designed for small o ...

Using Crawler4j, Jsoup, and JavaScript to retrieve modified attribute values

Currently, I am utilizing Crawler4j and Jsoup for web crawling and it's performing well with HTML text. However, some vital contents have default values hardcoded in CSS and then dynamically adjusted through JavaScript. For instance, there's a e ...

Mastering the art of utilizing $.get(url, function(data) in pure JavaScript

I am currently exploring how to achieve the equivalent of $.get(url,function(data) { code }; in pure JavaScript. function fetchImage(keyword){ if(!ACCESS_KEY){ alert("Please update your access key"); return; } var request = new XMLHttpRequ ...

If the handler of an event listener in jQuery requires a callback function, be sure to detach the event

Currently, I am facing a dilemma with a listener I have: $(document).on("keypress", function(e){ebClose(e,mpClose)}); I am exploring ways to dynamically delete this listener. The issue lies in the fact that I specifically want ebClose to receive mpClose ...

Parsing all HTML elements using Nokogiri

I've been searching everywhere and all I could find was how to use CSS selection with Nokogiri. What I really need is to completely remove all HTML tags. For instance, this: <html> <head><title>My webpage</title></head& ...

Using the include function in PHP may cause issues with the functionality of the isset() function

As a complete beginner in PHP programming, I've encountered an issue with my code. The isset() function doesn't seem to be working as expected and I'm not sure why. When I remove the isset() block, the data displays correctly. But when I in ...

What are the recommended breakpoints for a bootstrap 3 grid with a width of 1500px?

Hello there! I have a question regarding Bootstrap 3 grid. I need it to have a width of 1500px with a gutter width of 30px. Which breakpoints should be adjusted accordingly for this setup? ...

Scroll to value in a custom dropdown with AngularJS

How do I ensure the selected item in a listbox scrolls to the top? [http://jsfiddle.net/729nX/1/] I need help with a similar issue, but there are a few differences: 1) I want to use only AngularJS without jQuery. 2) My code is unique from the example pro ...

Display the status in the textbox once a dropdown value has been selected

I have a function that allows me to add shops. Within this function, I am able to select whether the shop is OPEN or CLOSED. The goal is for the status of the shop, either OPEN or CLOSED, to appear in a textbox on another modal. When creating a user and ...

Incorporating a function within another function to mitigate redundancy in code: A guide

Using jQuery in this instance, although that should not impact the response. Upon loading the page, two events are triggered: triggerEvent(SNVisitsForm); $('#email').blur(triggerEvent(SNEnterEmail)); The first event triggers when a user visit ...

Tips on altering the h2 color when hovering using h2:hover:after

I'm attempting to alter the color of my h2 element using h2:hover:after. Can someone guide me on how to achieve this? Here is what I have tried so far. h2 { font-size: 25px; } h2:after { content: ""; display: block; width: 14%; padding-to ...

Adjusting font size to perfectly fit within its confines

When using v-for to map out objects from an array into cards, it's important to keep the height consistent throughout the section. Manually adjusting text size with @media queries can be tedious and inelegant, requiring multiple rules for different sc ...

Benefits of utilizing minified AngularJS versions (Exploring the advantages of angular.min.js over angular.js, along with the inclusion of angular.min.js.map)

After introducing angular.min.js into my project, I encountered a problem. http://localhost:8000/AngularProject/angular.min.js.map 404 (Not Found) angular.min.js.map:1 Upon further investigation, I discovered that including angular.min.js.map resolve ...

A database table named after a pair of digits

My database tables are named "30" and "kev." When I query the table named "30," I receive the following error message: Warning: Invalid argument supplied for foreach() in # on line 94 However, when I query the kev table, I do get the desired results. B ...

Using mysqli_real_escape_string to secure an array that has been parsed through json and passed via ajax

Currently, I am working on parsing an array using Ajax. Jquery if (conceptName == "payall"){ var payall = confirm ("You are about to make a payment for some items."); if (payall == true ){ var checkedB = new Array(); $("input.NP:checkbox:checked") ...