Menu
Coddy logo textTech

תפריטים נפתחים

חלק מהיחידה JavaScript בפעולה במסלול ה-HTML של Coddy. שיעור 15 מתוך 27.

תפריטים נפתחים הם רכיבי ממשק משתמש שמציגים אפשרויות נוספות כשהם מופעלים. נהוג להשתמש בהם בניווט כדי לארגן תוכן בלי לתפוס יותר מדי מקום.

ראשית, ניצור את מבנה ה-HTML עבור תפריט נפתח בסיסי:

<div class="dropdown">
  <button class="dropdown-toggle">Menu</button>
  <div class="dropdown-menu">
    <a href="#">Option 1</a>
    <a href="#">Option 2</a>
    <a href="#">Option 3</a>
  </div>
</div>

עכשיו, נוסיף את JavaScript כדי להחליף את מצב הנראות של התפריט הנפתח:

// קבל את כפתור הפתיחה והסגירה של התפריט הנפתח
const dropdownToggle = document.querySelector('.dropdown-toggle');

// קבל את התפריט הנפתח
const dropdownMenu = document.querySelector('.dropdown-menu');

// הוסף מאזין לאירוע לחיצה לכפתור הפתיחה והסגירה
dropdownToggle.addEventListener('click', function() {
  // הפעל או בטל את המחלקה 'show' בתפריט הנפתח
  dropdownMenu.classList.toggle('show');
});

לבסוף, הוסף מעט CSS בסיסי כדי להסתיר/להציג את התפריט הנפתח:

.dropdown-menu {
  display: none;
}

.dropdown-menu.show {
  display: block;
}

כשתלחץ על כפתור "Menu", התפריט הנפתח יופיע. לחיצה עליו שוב תסתיר את התפריט.

challenge icon

אתגר

קל

צור תפריט נפתח שמוצג ומוסתר כשלוחצים על כפתור.

שלבים:

  1. ב-HTML:
    • הוסף לכפתור מאפיין onclick שקורא לפונקציה בשם toggleDropdown כשלוחצים עליו
  2. ב-JavaScript:
    • צור פונקציה בשם toggleDropdown
    • בתוך הפונקציה, החלף את מחלקת "show" של האלמנט שמזהה ה-ID שלו הוא “myDropdown”

נסו בעצמכם

<!DOCTYPE html>
<html>
<head>
  <title>Save the Forests</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header>
    <h1>Save the Forests</h1>
    <p>Even planting one or two trees makes a difference.</p>
  </header>

  <div class="dropdown">
    <button class="dropbtn">Learn More ▼</button>
    <div id="myDropdown" class="dropdown-content">
      <a href="#">Why forests matter</a>
      <a href="#">How to grow a tree</a>
      <a href="#">Community projects</a>
    </div>
  </div>

  <main>
    <section>
      <h2>Why Trees Are Important</h2>
      <p>
        Forests clean our air, give us oxygen, and are home to countless animals.  
        Each tree you plant helps fight climate change and supports life on Earth.
      </p>
    </section>
    <section>
      <h2> Start Small</h2>
      <p>
        Don’t wait for a big change. Start with just one or two trees in your yard or community.  
        Your small action inspires others!
      </p>
    </section>
  </main>

  <footer>
    <p> Together we can make the planet greener.</p>
  </footer>

  <script src="script.js"></script>
</body>
</html>
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה JavaScript בפעולה

תרגלו בעצמכם: Web אונליין