Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Funcionalidad de Filtrado | Construyendo el Sitio Web del Blog
Fundamentos del Desarrollo Web con IA

book
Funcionalidad de Filtrado

Objetivo

Por último, pero no menos importante, el paso final es agregar funcionalidad para filtrar los artículos por tema, lo cual se implementará usando JavaScript.

Posible Solicitud

¿Puedes implementar la función de filtrar artículos por tema usando botones HTML y JavaScript?

Resultado

archivo index.html

  • Añadimos un bloque nav al header donde se colocarán nuestros botones de filtrado;

  • Proporcionamos a cada artículo el atributo data-category y el valor correspondiente al tema;

  • Añadimos el enlace al archivo index.js antes de la etiqueta de cierre body.

archivo index.css
Añadimos algunos estilos para que los botones de filtrado se vean bonitos.

archivo index.js
Pegamos el script que implementa la lógica de filtrado.

Todo esto nos lo dijo ChaGPT. Seguimos sus instrucciones.

html

index.html

css

index.css

js

index.js

copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Blog</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<header>
<h1>Welcome to My Blog</h1>
<nav>
<button onclick="filterArticles('all')">All</button>
<button onclick="filterArticles('Environment')">Environment</button>
<button onclick="filterArticles('Health')">Health</button>
</nav>
</header>

<main>
<article data-category="Health">
<h2>Unlocking the Power of Daily Habits for Optimal Health</h2>
<p>
Maintaining optimal health is a multifaceted endeavor, often achieved through the
consistent practice of healthy habits. Nutrition plays a pivotal role in our overall
well-being, serving as the foundation for vitality and disease prevention. Embracing a
balanced diet rich in fruits, vegetables, lean proteins, and whole grains fuels our bodies
with essential nutrients while fortifying our immune systems. Moreover, prioritizing
hydration ensures proper bodily functions and supports cognitive performance. By
integrating mindful eating practices and staying hydrated, individuals can enhance their
energy levels, promote weight management, and reduce the risk of chronic conditions such
as heart disease and diabetes.
</p>
<img
src="https://images.unsplash.com/photo-1477332552946-cfb384aeaf1c?q=80&w=2940&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
alt="Unlocking the Power of Daily Habits for Optimal Health"
width="360"
/>
<p>
In addition to nutrition, regular physical activity is paramount for maintaining optimal
health. Engaging in moderate exercise for at least 30 minutes most days of the week offers
a myriad of benefits, including improved cardiovascular health, strengthened muscles and
bones, and enhanced mood. Furthermore, consistent exercise helps manage stress levels and
promotes better sleep quality, crucial components of overall well-being. By incorporating
enjoyable physical activities into daily routines, individuals can cultivate sustainable
habits that contribute to a healthier, more fulfilling life. Through the synergy of
nutritious eating and regular exercise, individuals can unlock the power of daily habits
to optimize their health and vitality.
</p>
<p>Category: <strong>Health</strong></p>
</article>

<article data-category="Environment">
<h2>The Crucial Role of Daily Actions in Environmental Preservation</h2>
<p>
Environmental preservation is a collective responsibility that hinges on the daily actions
of individuals. Simple yet impactful habits can significantly contribute to the health of
our planet. One such practice is reducing waste through mindful consumption and recycling.
By choosing reusable products, minimizing single-use plastics, and properly sorting
recyclables, individuals can decrease the amount of waste that ends up in landfills and
oceans. This, in turn, helps protect wildlife and reduces pollution. Moreover, supporting
sustainable products and practices, such as purchasing locally-sourced and eco-friendly
goods, can further diminish our environmental footprint.
</p>
<img
src="https://images.unsplash.com/photo-1535914254981-b5012eebbd15?q=80&w=2940&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
alt="The Crucial Role of Daily Actions in Environmental Preservation"
width="360"
/>
<p>
Another critical aspect of environmental preservation is energy conservation. Small
changes in our daily routines can lead to substantial energy savings. For instance,
turning off lights when not in use, unplugging electronic devices, and utilizing
energy-efficient appliances can significantly reduce household energy consumption.
Additionally, opting for public transportation, carpooling, or using alternative modes of
transport like cycling or walking can decrease greenhouse gas emissions. These practices
not only help mitigate climate change but also promote cleaner air and healthier
communities. By integrating these environmentally conscious habits into our daily lives,
we can collectively make a significant impact on preserving the planet for future
generations.
</p>
<p>Category: <strong>Environment</strong></p>
</article>

<article data-category="Health">
<h2>The Importance of Mental Health in Overall Well-Being</h2>
<p>
Mental health is an integral component of overall well-being, influencing how we think,
feel, and act in our daily lives. It plays a crucial role in determining how we handle
stress, relate to others, and make choices. Promoting mental health starts with
recognizing and addressing the signs of mental health issues, such as prolonged stress,
anxiety, and depression. Regular mental health check-ins, whether through self-reflection
or professional counseling, can help individuals manage their emotions and maintain a
balanced outlook on life. Prioritizing mental health can lead to improved relationships,
productivity, and a better quality of life.
</p>
<img
src="https://images.unsplash.com/photo-1506126613408-eca07ce68773?q=80&w=2202&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
alt="The Importance of Mental Health in Overall Well-Being"
width="360"
/>
<p>
Incorporating mental health practices into daily routines is essential for sustaining
mental well-being. Techniques such as mindfulness, meditation, and regular physical
activity can reduce stress and enhance mood. Mindfulness encourages present-moment
awareness, helping individuals manage overwhelming thoughts and emotions. Similarly,
meditation promotes relaxation and mental clarity, while physical activity releases
endorphins, which are natural mood lifters. Ensuring adequate sleep, maintaining a healthy
diet, and fostering social connections also contribute to mental resilience. By embedding
these practices into daily life, individuals can support their mental health, leading to a
more balanced and fulfilling life.
</p>
<p>Category: <strong>Health</strong></p>
</article>
</main>

<footer>
<p>&copy; 2024 My Blog. All rights reserved.</p>
</footer>

<script src="index.js"></script>
</body>
</html>

Estado del Sitio Web

Tutorial en Video

Aquí tienes. Lo lograste. Este es tu sitio web completo y totalmente funcional. ¡Buen trabajo!

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 6

Pregunte a AI

expand
ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

We use cookies to make your experience better!
some-alt