1602334800

Fast Pattern Searching with STUMPY

The Whole is Greater than the Sum of Its Parts

(Image by Author)

STUMPY is a powerful and scalable Python library for modern time series analysis and, at its core, efficiently computes something called a matrix profile. The goal of this multi-part series is to explain what the matrix profile is and how you can start leveraging STUMPY for all of your modern time series data mining tasks!

Note: These tutorials were originally featured in the STUMPY documentation.

Part 1: The Matrix Profile

Part 2: STUMPY Basics

Part 3: Time Series Chains

Part 4: Semantic Segmentation

Beyond Matrix Profiles

At the core of STUMPY, one can take any time series data and efficiently compute something called a matrix profile, which essentially scans along your entire times series with a fixed window size, `m`, and finds the exact nearest neighbor for every subsequence within your time series. A matrix profile allows you to determine if there are any conserved behaviors (i.e., conserved subsequences/patterns) within your data and, if so, it can tell you exactly where they are located within your time series. In a previous tutorial, we demonstrated how to use STUMPY to easily obtain a matrix profile, learned how to interpret the results, and discover meaningful motifs and discords. While this brute-force approach may be very useful when you don’t know what pattern or conserved behavior you are looking but, for sufficiently large datasets, it can become quite expensive to perform this exhaustive pairwise search.

However, if you already have a specific user defined pattern in mind then you don’t actually need to compute the full matrix profile! For example, maybe you’ve identified an interesting trading strategy based on historical stock market data and you’d like to see if that specific pattern may have been observed in the past within one or more stock ticker symbols. In that case, searching for a known pattern or “query” is actually quite straightforward and can be accomplished quickly by using the wonderful `core.mass` function in STUMPY.

In this short tutorial, we’ll take a simple known pattern of interest (i.e., a query subsequence) and we’ll search for this pattern in a separate independent time series. Let’s get started!

#python #towards-data-science #time-series-analysis #matrix-profile #stumpy

1637911366

Create a Product Filter and Search Using HTML, CSS & Javascript

Create a product filter that filters the products based on their categories using html, css & javascript . It also comes along with a search bar that searches the products based

Source Code:

HTML file

``````<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Product Filter And Search</title>
rel="stylesheet"
/>
<!-- Stylesheet -->
<body>
<div class="wrapper">
<div id="search-container">
<input
type="search"
id="search-input"
placeholder="Search product name here.."
/>
<button id="search">Search</button>
</div>
<div id="buttons">
<button class="button-value" onclick="filterProduct('all')">All</button>
<button class="button-value" onclick="filterProduct('Topwear')">
Topwear
</button>
<button class="button-value" onclick="filterProduct('Bottomwear')">
Bottomwear
</button>
<button class="button-value" onclick="filterProduct('Jacket')">
Jacket
</button>
<button class="button-value" onclick="filterProduct('Watch')">
Watch
</button>
</div>
<div id="products"></div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>``````

CSS file

``````* {
margin: 0;
box-sizing: border-box;
border: none;
outline: none;
font-family: "Poppins", sans-serif;
}
body {
background-color: #f5f8ff;
}
.wrapper {
width: 95%;
margin: 0 auto;
}
#search-container {
margin: 1em 0;
}
#search-container input {
background-color: transparent;
width: 40%;
border-bottom: 2px solid #110f29;
}
#search-container input:focus {
border-bottom-color: #6759ff;
}
#search-container button {
margin-left: 1em;
background-color: #6759ff;
color: #ffffff;
margin-top: 0.5em;
}
.button-value {
border: 2px solid #6759ff;
background-color: transparent;
color: #6759ff;
cursor: pointer;
}
.active {
background-color: #6759ff;
color: #ffffff;
}
#products {
display: grid;
grid-template-columns: auto auto auto;
grid-column-gap: 1.5em;
}
.card {
background-color: #ffffff;
max-width: 18em;
margin-top: 1em;
box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
text-align: center;
}
img {
max-width: 100%;
object-fit: contain;
height: 15em;
}
.container {
color: #110f29;
}
.container h5 {
font-weight: 500;
}
.hide {
display: none;
}
@media screen and (max-width: 720px) {
img {
max-width: 100%;
object-fit: contain;
height: 10em;
}
.card {
max-width: 10em;
margin-top: 1em;
}
#products {
grid-template-columns: auto auto;
grid-column-gap: 1em;
}
}``````

JavaScript file

``````let products = {
data: [
{
productName: "Regular White T-Shirt",
category: "Topwear",
price: "30",
image: "white-tshirt.jpg",
},
{
productName: "Beige Short Skirt",
category: "Bottomwear",
price: "49",
image: "short-skirt.jpg",
},
{
productName: "Sporty SmartWatch",
category: "Watch",
price: "99",
image: "sporty-smartwatch.jpg",
},
{
productName: "Basic Knitted Top",
category: "Topwear",
price: "29",
image: "knitted-top.jpg",
},
{
productName: "Black Leather Jacket",
category: "Jacket",
price: "129",
image: "black-leather-jacket.jpg",
},
{
productName: "Stylish Pink Trousers",
category: "Bottomwear",
price: "89",
image: "pink-trousers.jpg",
},
{
productName: "Brown Men's Jacket",
category: "Jacket",
price: "189",
image: "brown-jacket.jpg",
},
{
productName: "Comfy Gray Pants",
category: "Bottomwear",
price: "49",
image: "comfy-gray-pants.jpg",
},
],
};

for (let i of products.data) {
//Create Card
let card = document.createElement("div");
//Card should have category and should stay hidden initially
//image div
let imgContainer = document.createElement("div");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
//container
let container = document.createElement("div");
//product name
let name = document.createElement("h5");
name.innerText = i.productName.toUpperCase();
container.appendChild(name);
//price
let price = document.createElement("h6");
price.innerText = "\$" + i.price;
container.appendChild(price);

card.appendChild(container);
document.getElementById("products").appendChild(card);
}

//parameter passed from button (Parameter same as category)
function filterProduct(value) {
//Button class code
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
//check if value equals innerText
if (value.toUpperCase() == button.innerText.toUpperCase()) {
} else {
button.classList.remove("active");
}
});

//select all cards
let elements = document.querySelectorAll(".card");
//loop through all cards
elements.forEach((element) => {
//display all cards on 'all' button click
if (value == "all") {
element.classList.remove("hide");
} else {
//Check if element contains category class
if (element.classList.contains(value)) {
//display element based on category
element.classList.remove("hide");
} else {
//hide other elements
}
}
});
}

//Search button click
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".product-name");
let cards = document.querySelectorAll(".card");

//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others
}
});
});

filterProduct("all");
};``````

1637911881

Tạo Bộ lọc Sản phẩm và Tìm kiếm Sử dụng HTML, CSS & Javascript

Chào mừng đến với hướng dẫn hôm nay. Trong hướng dẫn hôm nay, chúng ta sẽ học cách xây dựng bộ lọc và tìm kiếm sản phẩm. Để tạo dự án này, chúng ta cần HTML, CSS và Javascript. Vì đây là một dự án khá nâng cao, tôi sẽ không giới thiệu nó cho người mới bắt đầu sử dụng javascript. Nếu bạn là một trung cấp hoặc chuyên gia về javascript, bạn chắc chắn có thể tiếp tục và tạo ra cái này.

Hãy để chúng tôi có một cái nhìn tổng quan về dự án này thực sự là gì. Dự án bao gồm một loạt các thẻ sản phẩm. Mỗi thẻ này có tên, giá và danh mục được gán cho chúng. Phía trên các thẻ này, có một thanh tìm kiếm nơi người dùng có thể tìm kiếm một sản phẩm dựa trên tên của nó.

Bên dưới thanh tìm kiếm, có một nhóm các nút. Mỗi nút này có một tên danh mục trên đó. Khi người dùng nhấp vào bất kỳ nút nào trong số các nút này, các sản phẩm tương ứng với danh mục cụ thể đó sẽ được hiển thị.

Cấu trúc thư mục dự án:

Bây giờ trước tiên chúng ta hãy tạo cấu trúc thư mục dự án để chúng ta có thể bắt đầu viết mã. Chúng tôi bắt đầu bằng cách tạo một thư mục dự án có tên - 'Bộ lọc và Tìm kiếm Sản phẩm'. Bên trong thư mục này, chúng tôi tạo ba tệp. Đầu tiên là `index.html`, thứ hai là `style.css`và thứ ba là `script.js`. Các tệp này lần lượt là tài liệu HTML, biểu định kiểu và tệp tập lệnh.

HTML:

Chúng tôi bắt đầu với mã HTML. Trước tiên, hãy sao chép đoạn mã dưới đây và dán vào tệp HTML của bạn.

``````<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Product Filter And Search</title>
rel="stylesheet"
/>
<!-- Stylesheet -->
<body>
<div class="wrapper">
<div id="search-container">
<input
type="search"
id="search-input"
placeholder="Search product name here.."
/>
<button id="search">Search</button>
</div>
<div id="buttons">
<button class="button-value" onclick="filterProduct('all')">All</button>
<button class="button-value" onclick="filterProduct('Topwear')">
Topwear
</button>
<button class="button-value" onclick="filterProduct('Bottomwear')">
Bottomwear
</button>
<button class="button-value" onclick="filterProduct('Jacket')">
Jacket
</button>
<button class="button-value" onclick="filterProduct('Watch')">
Watch
</button>
</div>
<div id="products"></div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>``````

CSS:

Tiếp theo để thêm kiểu cho dự án này, chúng tôi sử dụng CSS. Bây giờ sao chép mã bên dưới và dán nó vào tệp CSS của bạn.

``````* {
margin: 0;
box-sizing: border-box;
border: none;
outline: none;
font-family: "Poppins", sans-serif;
}
body {
background-color: #f5f8ff;
}
.wrapper {
width: 95%;
margin: 0 auto;
}
#search-container {
margin: 1em 0;
}
#search-container input {
background-color: transparent;
width: 40%;
border-bottom: 2px solid #110f29;
}
#search-container input:focus {
border-bottom-color: #6759ff;
}
#search-container button {
margin-left: 1em;
background-color: #6759ff;
color: #ffffff;
margin-top: 0.5em;
}
.button-value {
border: 2px solid #6759ff;
background-color: transparent;
color: #6759ff;
cursor: pointer;
}
.active {
background-color: #6759ff;
color: #ffffff;
}
#products {
display: grid;
grid-template-columns: auto auto auto;
grid-column-gap: 1.5em;
}
.card {
background-color: #ffffff;
max-width: 18em;
margin-top: 1em;
box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
text-align: center;
}
img {
max-width: 100%;
object-fit: contain;
height: 15em;
}
.container {
color: #110f29;
}
.container h5 {
font-weight: 500;
}
.hide {
display: none;
}
@media screen and (max-width: 720px) {
img {
max-width: 100%;
object-fit: contain;
height: 10em;
}
.card {
max-width: 10em;
margin-top: 1em;
}
#products {
grid-template-columns: auto auto;
grid-column-gap: 1em;
}
}``````

Javascript:

Cuối cùng, chúng ta cần thêm chức năng vào bộ lọc và cũng thực hiện chức năng tìm kiếm. Để làm cho nó hoạt động, chúng tôi thêm javascript. Sao chép mã được cung cấp bên dưới và dán vào tệp javascript của bạn.

``````let products = {
data: [
{
productName: "Regular White T-Shirt",
category: "Topwear",
price: "30",
image: "white-tshirt.jpg",
},
{
productName: "Beige Short Skirt",
category: "Bottomwear",
price: "49",
image: "short-skirt.jpg",
},
{
productName: "Sporty SmartWatch",
category: "Watch",
price: "99",
image: "sporty-smartwatch.jpg",
},
{
productName: "Basic Knitted Top",
category: "Topwear",
price: "29",
image: "knitted-top.jpg",
},
{
productName: "Black Leather Jacket",
category: "Jacket",
price: "129",
image: "black-leather-jacket.jpg",
},
{
productName: "Stylish Pink Trousers",
category: "Bottomwear",
price: "89",
image: "pink-trousers.jpg",
},
{
productName: "Brown Men's Jacket",
category: "Jacket",
price: "189",
image: "brown-jacket.jpg",
},
{
productName: "Comfy Gray Pants",
category: "Bottomwear",
price: "49",
image: "comfy-gray-pants.jpg",
},
],
};

for (let i of products.data) {
//Create Card
let card = document.createElement("div");
//Card should have category and should stay hidden initially
//image div
let imgContainer = document.createElement("div");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
//container
let container = document.createElement("div");
//product name
let name = document.createElement("h5");
name.innerText = i.productName.toUpperCase();
container.appendChild(name);
//price
let price = document.createElement("h6");
price.innerText = "\$" + i.price;
container.appendChild(price);

card.appendChild(container);
document.getElementById("products").appendChild(card);
}

//parameter passed from button (Parameter same as category)
function filterProduct(value) {
//Button class code
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
//check if value equals innerText
if (value.toUpperCase() == button.innerText.toUpperCase()) {
} else {
button.classList.remove("active");
}
});

//select all cards
let elements = document.querySelectorAll(".card");
//loop through all cards
elements.forEach((element) => {
//display all cards on 'all' button click
if (value == "all") {
element.classList.remove("hide");
} else {
//Check if element contains category class
if (element.classList.contains(value)) {
//display element based on category
element.classList.remove("hide");
} else {
//hide other elements
}
}
});
}

//Search button click
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".product-name");
let cards = document.querySelectorAll(".card");

//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others
}
});
});

filterProduct("all");
};``````

Bộ lọc và tìm kiếm sản phẩm của bạn hiện đã sẵn sàng. Tôi hy vọng bạn thích hướng dẫn.

1637932920

Erstellen Sie Such- und Produktfilter mit HTML, CSS und Javascript

Willkommen zum heutigen Tutorial. Im heutigen Tutorial erfahren Sie, wie Sie Filter erstellen und nach Produkten suchen. Um dieses Projekt zu erstellen, benötigen wir HTML, CSS und Javascript. Da dies ein ziemlich fortgeschrittenes Projekt ist, würde ich es keinem Javascript-Anfänger empfehlen. Wenn Sie ein Fortgeschrittener oder Experte in Javascript sind, können Sie auf jeden Fall weitermachen und dieses machen.

Lassen Sie uns einen Überblick darüber geben, was dieses Projekt wirklich ist. Das Projekt umfasst eine Reihe von Produktkarten. Jeder dieser Karten ist ein Name, ein Preis und eine Kategorie zugeordnet. Über diesen Tags befindet sich eine Suchleiste, in der Benutzer anhand des Namens nach einem Produkt suchen können.

Unterhalb der Suchleiste befindet sich eine Gruppe von Schaltflächen. Jede dieser Schaltflächen hat einen Kategorienamen. Wenn der Benutzer auf eine dieser Schaltflächen klickt, werden die Produkte angezeigt, die dieser bestimmten Kategorie entsprechen.

Projektordnerstruktur:

Lassen Sie uns nun zunächst die Projektverzeichnisstruktur erstellen, damit wir mit dem Codieren beginnen können. Wir beginnen damit, einen Projektordner mit dem Namen "Filters and Product Search" zu erstellen. In diesem Ordner erstellen wir drei Dateien. Das erste ist `index.html`, das zweite ist `style.css`und das dritte ist `script.js`. Diese Dateien sind HTML-Dokumente, Stylesheets bzw. Skriptdateien.

HTML-Code:

Wir beginnen mit dem HTML-Code. Kopieren Sie zunächst den folgenden Code und fügen Sie ihn in Ihre HTML-Datei ein.

``````<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Product Filter And Search</title>
rel="stylesheet"
/>
<!-- Stylesheet -->
<body>
<div class="wrapper">
<div id="search-container">
<input
type="search"
id="search-input"
placeholder="Search product name here.."
/>
<button id="search">Search</button>
</div>
<div id="buttons">
<button class="button-value" onclick="filterProduct('all')">All</button>
<button class="button-value" onclick="filterProduct('Topwear')">
Topwear
</button>
<button class="button-value" onclick="filterProduct('Bottomwear')">
Bottomwear
</button>
<button class="button-value" onclick="filterProduct('Jacket')">
Jacket
</button>
<button class="button-value" onclick="filterProduct('Watch')">
Watch
</button>
</div>
<div id="products"></div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>``````

CSS:

Um diesem Projekt Stile hinzuzufügen, verwenden wir CSS. Kopieren Sie nun den folgenden Code und fügen Sie ihn in Ihre CSS-Datei ein.

``````* {
margin: 0;
box-sizing: border-box;
border: none;
outline: none;
font-family: "Poppins", sans-serif;
}
body {
background-color: #f5f8ff;
}
.wrapper {
width: 95%;
margin: 0 auto;
}
#search-container {
margin: 1em 0;
}
#search-container input {
background-color: transparent;
width: 40%;
border-bottom: 2px solid #110f29;
}
#search-container input:focus {
border-bottom-color: #6759ff;
}
#search-container button {
margin-left: 1em;
background-color: #6759ff;
color: #ffffff;
margin-top: 0.5em;
}
.button-value {
border: 2px solid #6759ff;
background-color: transparent;
color: #6759ff;
cursor: pointer;
}
.active {
background-color: #6759ff;
color: #ffffff;
}
#products {
display: grid;
grid-template-columns: auto auto auto;
grid-column-gap: 1.5em;
}
.card {
background-color: #ffffff;
max-width: 18em;
margin-top: 1em;
box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
text-align: center;
}
img {
max-width: 100%;
object-fit: contain;
height: 15em;
}
.container {
color: #110f29;
}
.container h5 {
font-weight: 500;
}
.hide {
display: none;
}
@media screen and (max-width: 720px) {
img {
max-width: 100%;
object-fit: contain;
height: 10em;
}
.card {
max-width: 10em;
margin-top: 1em;
}
#products {
grid-template-columns: auto auto;
grid-column-gap: 1em;
}
}``````

Javascript:

Schließlich müssen wir dem Filter Funktionen hinzufügen und auch die Suchfunktion implementieren. Damit es funktioniert, fügen wir Javascript hinzu. Kopieren Sie den unten angegebenen Code und fügen Sie ihn in Ihre Javascript-Datei ein.

``````let products = {
data: [
{
productName: "Regular White T-Shirt",
category: "Topwear",
price: "30",
image: "white-tshirt.jpg",
},
{
productName: "Beige Short Skirt",
category: "Bottomwear",
price: "49",
image: "short-skirt.jpg",
},
{
productName: "Sporty SmartWatch",
category: "Watch",
price: "99",
image: "sporty-smartwatch.jpg",
},
{
productName: "Basic Knitted Top",
category: "Topwear",
price: "29",
image: "knitted-top.jpg",
},
{
productName: "Black Leather Jacket",
category: "Jacket",
price: "129",
image: "black-leather-jacket.jpg",
},
{
productName: "Stylish Pink Trousers",
category: "Bottomwear",
price: "89",
image: "pink-trousers.jpg",
},
{
productName: "Brown Men's Jacket",
category: "Jacket",
price: "189",
image: "brown-jacket.jpg",
},
{
productName: "Comfy Gray Pants",
category: "Bottomwear",
price: "49",
image: "comfy-gray-pants.jpg",
},
],
};

for (let i of products.data) {
//Create Card
let card = document.createElement("div");
//Card should have category and should stay hidden initially
//image div
let imgContainer = document.createElement("div");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
//container
let container = document.createElement("div");
//product name
let name = document.createElement("h5");
name.innerText = i.productName.toUpperCase();
container.appendChild(name);
//price
let price = document.createElement("h6");
price.innerText = "\$" + i.price;
container.appendChild(price);

card.appendChild(container);
document.getElementById("products").appendChild(card);
}

//parameter passed from button (Parameter same as category)
function filterProduct(value) {
//Button class code
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
//check if value equals innerText
if (value.toUpperCase() == button.innerText.toUpperCase()) {
} else {
button.classList.remove("active");
}
});

//select all cards
let elements = document.querySelectorAll(".card");
//loop through all cards
elements.forEach((element) => {
//display all cards on 'all' button click
if (value == "all") {
element.classList.remove("hide");
} else {
//Check if element contains category class
if (element.classList.contains(value)) {
//display element based on category
element.classList.remove("hide");
} else {
//hide other elements
}
}
});
}

//Search button click
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".product-name");
let cards = document.querySelectorAll(".card");

//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others
}
});
});

filterProduct("all");
};``````

Ihre Produktsuche und -filterung ist nun fertig. Ich hoffe, Ihnen hat das Tutorial gefallen.

1637912634

Cree filtros de búsqueda y de productos utilizando Javascript

Bienvenido al tutorial de hoy. En el tutorial de hoy, aprenderemos cómo crear filtros y buscar productos. Para crear este proyecto, necesitamos HTML, CSS y Javascript. Dado que este es un proyecto bastante avanzado, no se lo recomendaría a un principiante de JavaScript. Si eres un intermedio o un experto en javascript, definitivamente puedes seguir adelante y hacer este.

Tengamos una visión general de lo que realmente es este proyecto. El proyecto incluye una serie de fichas de producto. Cada una de estas tarjetas tiene asignado un nombre, precio y categoría. Por encima de estas etiquetas, hay una barra de búsqueda donde los usuarios pueden buscar un producto según su nombre.

Debajo de la barra de búsqueda, hay un grupo de botones. Cada uno de estos botones tiene un nombre de categoría. Cuando el usuario haga clic en cualquiera de estos botones, se mostrarán los productos correspondientes a esa categoría en particular.

Estructura de la carpeta del proyecto:

Ahora, primero creemos la estructura del directorio del proyecto para que podamos comenzar a codificar. Comenzamos creando una carpeta de proyecto llamada - 'Filtros y búsqueda de productos'. Dentro de esta carpeta creamos tres archivos. El primero es `index.html`, el segundo es `style.css`y el tercero es `script.js`. Estos archivos son documentos HTML, hojas de estilo y archivos de script, respectivamente.

HTML:

Empezamos con el código HTML. Primero, copie el código a continuación y péguelo en su archivo HTML.

``````<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Product Filter And Search</title>
rel="stylesheet"
/>
<!-- Stylesheet -->
<body>
<div class="wrapper">
<div id="search-container">
<input
type="search"
id="search-input"
placeholder="Search product name here.."
/>
<button id="search">Search</button>
</div>
<div id="buttons">
<button class="button-value" onclick="filterProduct('all')">All</button>
<button class="button-value" onclick="filterProduct('Topwear')">
Topwear
</button>
<button class="button-value" onclick="filterProduct('Bottomwear')">
Bottomwear
</button>
<button class="button-value" onclick="filterProduct('Jacket')">
Jacket
</button>
<button class="button-value" onclick="filterProduct('Watch')">
Watch
</button>
</div>
<div id="products"></div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>``````

CSS:

A continuación, para agregar estilos a este proyecto, usamos CSS. Ahora copie el código a continuación y péguelo en su archivo CSS.

``````* {
margin: 0;
box-sizing: border-box;
border: none;
outline: none;
font-family: "Poppins", sans-serif;
}
body {
background-color: #f5f8ff;
}
.wrapper {
width: 95%;
margin: 0 auto;
}
#search-container {
margin: 1em 0;
}
#search-container input {
background-color: transparent;
width: 40%;
border-bottom: 2px solid #110f29;
}
#search-container input:focus {
border-bottom-color: #6759ff;
}
#search-container button {
margin-left: 1em;
background-color: #6759ff;
color: #ffffff;
margin-top: 0.5em;
}
.button-value {
border: 2px solid #6759ff;
background-color: transparent;
color: #6759ff;
cursor: pointer;
}
.active {
background-color: #6759ff;
color: #ffffff;
}
#products {
display: grid;
grid-template-columns: auto auto auto;
grid-column-gap: 1.5em;
}
.card {
background-color: #ffffff;
max-width: 18em;
margin-top: 1em;
box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
text-align: center;
}
img {
max-width: 100%;
object-fit: contain;
height: 15em;
}
.container {
color: #110f29;
}
.container h5 {
font-weight: 500;
}
.hide {
display: none;
}
@media screen and (max-width: 720px) {
img {
max-width: 100%;
object-fit: contain;
height: 10em;
}
.card {
max-width: 10em;
margin-top: 1em;
}
#products {
grid-template-columns: auto auto;
grid-column-gap: 1em;
}
}``````

Javascript:

Finalmente, necesitamos agregar funcionalidad al filtro y también implementar la función de búsqueda. Para que funcione, agregamos javascript. Copie el código que se proporciona a continuación y péguelo en su archivo javascript.

``````let products = {
data: [
{
productName: "Regular White T-Shirt",
category: "Topwear",
price: "30",
image: "white-tshirt.jpg",
},
{
productName: "Beige Short Skirt",
category: "Bottomwear",
price: "49",
image: "short-skirt.jpg",
},
{
productName: "Sporty SmartWatch",
category: "Watch",
price: "99",
image: "sporty-smartwatch.jpg",
},
{
productName: "Basic Knitted Top",
category: "Topwear",
price: "29",
image: "knitted-top.jpg",
},
{
productName: "Black Leather Jacket",
category: "Jacket",
price: "129",
image: "black-leather-jacket.jpg",
},
{
productName: "Stylish Pink Trousers",
category: "Bottomwear",
price: "89",
image: "pink-trousers.jpg",
},
{
productName: "Brown Men's Jacket",
category: "Jacket",
price: "189",
image: "brown-jacket.jpg",
},
{
productName: "Comfy Gray Pants",
category: "Bottomwear",
price: "49",
image: "comfy-gray-pants.jpg",
},
],
};

for (let i of products.data) {
//Create Card
let card = document.createElement("div");
//Card should have category and should stay hidden initially
//image div
let imgContainer = document.createElement("div");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
//container
let container = document.createElement("div");
//product name
let name = document.createElement("h5");
name.innerText = i.productName.toUpperCase();
container.appendChild(name);
//price
let price = document.createElement("h6");
price.innerText = "\$" + i.price;
container.appendChild(price);

card.appendChild(container);
document.getElementById("products").appendChild(card);
}

//parameter passed from button (Parameter same as category)
function filterProduct(value) {
//Button class code
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
//check if value equals innerText
if (value.toUpperCase() == button.innerText.toUpperCase()) {
} else {
button.classList.remove("active");
}
});

//select all cards
let elements = document.querySelectorAll(".card");
//loop through all cards
elements.forEach((element) => {
//display all cards on 'all' button click
if (value == "all") {
element.classList.remove("hide");
} else {
//Check if element contains category class
if (element.classList.contains(value)) {
//display element based on category
element.classList.remove("hide");
} else {
//hide other elements
}
}
});
}

//Search button click
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".product-name");
let cards = document.querySelectorAll(".card");

//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others
}
});
});

filterProduct("all");
};``````

Su búsqueda y filtro de productos ya están listos. Espero que hayan disfrutado el tutorial.

1637913836

Создание фильтров поиска и товаров с помощью Javascript

Добро пожаловать в сегодняшнее руководство. В сегодняшнем руководстве мы узнаем, как создавать фильтры и искать товары. Для создания этого проекта нам понадобятся HTML, CSS и Javascript. Поскольку это довольно продвинутый проект, я бы не рекомендовал его новичку в javascript. Если вы средний уровень или эксперт в javascript, вы определенно можете сделать это.

Давайте посмотрим, что это за проект на самом деле. В проект входит серия карточек продуктов. У каждой из этих карт есть название, цена и категория. Над этими тегами находится панель поиска, где пользователи могут искать продукт по его названию.

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

Структура папок проекта:

Теперь давайте сначала создадим структуру каталогов проекта, чтобы мы могли начать кодирование. Начнем с создания папки проекта с названием «Фильтры и поиск продуктов». Внутри этой папки мы создаем три файла. Первый есть `index.html`, второй есть `style.css`и третий есть `script.js`. Эти файлы представляют собой HTML-документы, таблицы стилей и файлы сценариев соответственно.

HTML:

Начнем с HTML-кода. Сначала скопируйте приведенный ниже код и вставьте его в свой HTML-файл.

``````<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Product Filter And Search</title>
rel="stylesheet"
/>
<!-- Stylesheet -->
<body>
<div class="wrapper">
<div id="search-container">
<input
type="search"
id="search-input"
placeholder="Search product name here.."
/>
<button id="search">Search</button>
</div>
<div id="buttons">
<button class="button-value" onclick="filterProduct('all')">All</button>
<button class="button-value" onclick="filterProduct('Topwear')">
Topwear
</button>
<button class="button-value" onclick="filterProduct('Bottomwear')">
Bottomwear
</button>
<button class="button-value" onclick="filterProduct('Jacket')">
Jacket
</button>
<button class="button-value" onclick="filterProduct('Watch')">
Watch
</button>
</div>
<div id="products"></div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>``````

CSS:

Далее, чтобы добавить стили в этот проект, мы используем CSS. Теперь скопируйте приведенный ниже код и вставьте его в свой файл CSS.

``````* {
margin: 0;
box-sizing: border-box;
border: none;
outline: none;
font-family: "Poppins", sans-serif;
}
body {
background-color: #f5f8ff;
}
.wrapper {
width: 95%;
margin: 0 auto;
}
#search-container {
margin: 1em 0;
}
#search-container input {
background-color: transparent;
width: 40%;
border-bottom: 2px solid #110f29;
}
#search-container input:focus {
border-bottom-color: #6759ff;
}
#search-container button {
margin-left: 1em;
background-color: #6759ff;
color: #ffffff;
margin-top: 0.5em;
}
.button-value {
border: 2px solid #6759ff;
background-color: transparent;
color: #6759ff;
cursor: pointer;
}
.active {
background-color: #6759ff;
color: #ffffff;
}
#products {
display: grid;
grid-template-columns: auto auto auto;
grid-column-gap: 1.5em;
}
.card {
background-color: #ffffff;
max-width: 18em;
margin-top: 1em;
box-shadow: 1em 2em 2.5em rgba(1, 2, 68, 0.08);
}
.image-container {
text-align: center;
}
img {
max-width: 100%;
object-fit: contain;
height: 15em;
}
.container {
color: #110f29;
}
.container h5 {
font-weight: 500;
}
.hide {
display: none;
}
@media screen and (max-width: 720px) {
img {
max-width: 100%;
object-fit: contain;
height: 10em;
}
.card {
max-width: 10em;
margin-top: 1em;
}
#products {
grid-template-columns: auto auto;
grid-column-gap: 1em;
}
}``````

Javascript:

Наконец, нам нужно добавить функциональность к фильтру, а также реализовать функцию поиска. Чтобы он заработал, мы добавляем javascript. Скопируйте приведенный ниже код и вставьте его в свой файл javascript.

``````let products = {
data: [
{
productName: "Regular White T-Shirt",
category: "Topwear",
price: "30",
image: "white-tshirt.jpg",
},
{
productName: "Beige Short Skirt",
category: "Bottomwear",
price: "49",
image: "short-skirt.jpg",
},
{
productName: "Sporty SmartWatch",
category: "Watch",
price: "99",
image: "sporty-smartwatch.jpg",
},
{
productName: "Basic Knitted Top",
category: "Topwear",
price: "29",
image: "knitted-top.jpg",
},
{
productName: "Black Leather Jacket",
category: "Jacket",
price: "129",
image: "black-leather-jacket.jpg",
},
{
productName: "Stylish Pink Trousers",
category: "Bottomwear",
price: "89",
image: "pink-trousers.jpg",
},
{
productName: "Brown Men's Jacket",
category: "Jacket",
price: "189",
image: "brown-jacket.jpg",
},
{
productName: "Comfy Gray Pants",
category: "Bottomwear",
price: "49",
image: "comfy-gray-pants.jpg",
},
],
};

for (let i of products.data) {
//Create Card
let card = document.createElement("div");
//Card should have category and should stay hidden initially
//image div
let imgContainer = document.createElement("div");
//img tag
let image = document.createElement("img");
image.setAttribute("src", i.image);
imgContainer.appendChild(image);
card.appendChild(imgContainer);
//container
let container = document.createElement("div");
//product name
let name = document.createElement("h5");
name.innerText = i.productName.toUpperCase();
container.appendChild(name);
//price
let price = document.createElement("h6");
price.innerText = "\$" + i.price;
container.appendChild(price);

card.appendChild(container);
document.getElementById("products").appendChild(card);
}

//parameter passed from button (Parameter same as category)
function filterProduct(value) {
//Button class code
let buttons = document.querySelectorAll(".button-value");
buttons.forEach((button) => {
//check if value equals innerText
if (value.toUpperCase() == button.innerText.toUpperCase()) {
} else {
button.classList.remove("active");
}
});

//select all cards
let elements = document.querySelectorAll(".card");
//loop through all cards
elements.forEach((element) => {
//display all cards on 'all' button click
if (value == "all") {
element.classList.remove("hide");
} else {
//Check if element contains category class
if (element.classList.contains(value)) {
//display element based on category
element.classList.remove("hide");
} else {
//hide other elements
}
}
});
}

//Search button click
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".product-name");
let cards = document.querySelectorAll(".card");

//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others