Удалить ACTIVE классы от всех других кнопок, когда я нажимаю другую кнопку в ванильном JavaScript - PullRequest
0 голосов
/ 20 января 2019

Я хочу назначить «активный» кнопке, на которую я нажал, и удалить активную с других кнопок, когда я делаю это, я хочу сделать это в Vanilla JS, так как я хочу практиковать свои навыки.Я пробовал подобные проблемы на SO, но я не могу заставить свой код работать.

В конечном итоге я хочу создать фильтр галереи для изображений, взятых из моей БД в PHP, который я добавил в свой код, как виднониже на основе кнопки, которая активна, я хочу показать / скрыть категории.Изображение получает class = someCategory из столбца image_category в моей БД.

Помощь приветствуется.

Я пытался рассмотреть аналогичные проблемы.Но мне не удалось заставить его работать.

Vanilla JS удаляет класс из всех других элементов, кроме 'активного' класса

HTML & PHP CODE:

     <div id="category-buttons">
    <h5>Choose image category</h5>
      <button id="All" class="catgory-button active" >All Categories</button>
      <button id="CNC_Machining_button" class="catgory-button">CNC_Machining</button>
      <button id="HP_Die_Casting" class="catgory-button">HP Die Casting</button>
      <button id="Iron_Casting" class="catgory-button">Iron Casting</button>
      <button id="Steel_Casting" class="catgory-button">Steel Casting</button>
      <button id="Precision_Casting" class="catgory-button">Precision Casting</button>
      <button id="Aluminium_Casting" class="catgory-button">Aluminum Casting</button>
    </div>


<section class="gallery-links">
<div class="wrapper">

  <h2 class="product-gallery-title">Product Gallery</h2>

  <div class="gallery-container">
    <?php
    include_once 'includes/dbh.inc.php';

    $sql = 'SELECT * FROM gallery ORDER BY orderGallery DESC';
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt,$sql)) {
      echo 'SQL statement failed!';
    } else {
      mysqli_stmt_execute($stmt);
      $result = mysqli_stmt_get_result($stmt);

      while ($row = mysqli_fetch_assoc($result)) {
        //what's echoed out by the database

        echo '  <a class="images '.$row["image_category"].'" style="background-repeat:no-repeat; background-image: url(gallery/'.$row["imgFullNameGallery"].')">
                <div class="color-overlay">
                <h3>'.$row["titleGallery"].'</h3>
                <p>'.$row["descGallery"].'</p>
                </div>
                </a>';
      }
    }


    ?>  

  </div>
 </div>

<?php

Код JS:

    let btns = Array.from(document.querySelectorAll('.category-button'));

    const handleClick = (e) => {
      e.preventDefault();
      btns.forEach(node => {
        node.classList.remove('active');
      });
      e.currentTarget.classList.add('active');
    }

    btns.forEach(node => {
      node.addEventListener('click', handleClick)
    });

Соответствующий код CSS:

    #category-buttons {
    float: left;
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    width: 12.5%;
    margin: 10vh 10px;
    }

    .category-button {
    padding: 20px;
    margin: 2px 0;;
    color: white;
    background: rgb(153, 124, 124);

    }

    .product-gallery-title {
    text-transform: uppercase;
    }

    .wrapper {
    text-align: center;
    width: 65%;
    margin: auto;
    }

    .gallery-container {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 13px;
    margin: auto;
    width: 100%;
    background: rgb(236, 236, 236);
    justify-content: center;
    }

    .images{
    height: 300px;
    width: 300px;
    max-width: 300px;
    max-height: 300px;
    text-decoration: none;
    }

ОжидаетсяРезультат: При нажатии кнопка получает active класс, а другие кнопки в области видимости теряют их.

1 Ответ

0 голосов
/ 20 января 2019

Например, вы можете сохранить активную кнопку в глобальной переменной и использовать эту переменную для удаления класса из нее при нажатии другой кнопки.

Так что-то вроде этого:

let btns = Array.from(document.querySelectorAll('.category_btn'));
let activeButton = null;

// The button which would be used to add 'active' class to
// all the buttons.
let allButton = document.querySelector('#All');

const handleClick = (e) => {
  e.preventDefault();
  e.currentTarget.classList.add('active');
  // Checks that the activeButton is defined (initially it's null).
  // Also checks that the button that was clicked is not the button which is
  // already active to avoid removing the active class on double click.
  if (activeButton != null && activeButton != e.currentTarget) {
    activeButton.classList.remove('active');
  }
  activeButton = e.currentTarget;
}

btns.forEach(node => {
  node.addEventListener('click', handleClick)
});

// Listen to a click event from the "allButton" and when it's clicked,
// loop through the buttons array and add 'active' class to all buttons
// in it.
allButton.addEventListener('click', function() {
    btns.forEach(btn => {
        btn.classList.add('active');
    })
});

В настоящее время я нигде не могу проверить и убедиться, что это работает, но я не вижу причин, по которым это не будет работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...