Home > OS >  Filtering data by category
Filtering data by category

Time:09-23

I have a javascript function that filters categories. There is also interleaving of lists in php.blade.

The problem is that alternation only works when filtering has All, and when we select a specific category, alternation does not work. How can this be fixed?

JavaScript

$('.category-filter_item').click(function(){
    $('.category-filter_item').removeClass('active')
    $(this).addClass('active')
    var dataFilter = $(this).attr('data-filter');
    $('.blog-list').hide()
    $(dataFilter).show()
})

php.blade

@extends('layouts.app')

@section('content')
<div class="container">
<div class="category-filter" id="filter">
    <div class="category-filter_item active" data-filter="*">All</div>
    @foreach($categories as $category)
    <div class="category-filter_item" data-filter=".category_{{$category->id}}">{{ $category->title }}</div>
    @endforeach
</div>

@foreach ($blogs as $index => $blog)
    <div class="blog-list">
        @if ($index % 2 === 1)  //Alternation
            <div class="blog blog--left" >
                <h2 class="blog_title">{{ $blog->title }}</h2>
            </div>
        @else

            <div class="blog blog--right">
                <h2 class="blog_title">{{ $blog->title }}</h2>
            </div>
        @endif
    </div>
@endforeach
</div>
@endsection

Controller

public function index()
    {
        $blogs = Blog::all();
        $categories = Category:all();

        return view('blog', compact('blogs', 'categories'));
    }

CodePudding user response:

Change the way of styling. currently, you are using the blog--left and blog--right for the left and right section remove that class from the div and apply the below style to the style.

.blog {
    width: 50%;
}

CodePudding user response:

Alternation doesn't work, because you have your "alternation" implemented with PHP. PHP - is server side. You are implementing filtering on js - clients side. So when you select any filter you page (html) is not re-rendering (@foreach ($blogs as $index => $blog) is not running anymore because it is PHP). So my suggestion would be:

  • remove classes blog--left, blog--right
  • add style for the .blog class .blog{width:50%; float: left;} (if your .blog has any margins you can try width 49% or less)
  • Related