jQuery toggleClass example

Toggle class name on click in jQuery

by adamovic

HTML

<!DOCTYPE html>

<html lang="en">

  <head>

    <script defer src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script defer src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
    <script>
      if (typeof whenDocReady === "function") {
        // already declared, do nothing
      } else {
        function whenDocReady(fn) {
          // see if DOM is already available
          if (document.readyState === "complete" || document.readyState === "interactive") {
            // call on next available tick
            setTimeout(fn, 1);
          } else {
            document.addEventListener("DOMContentLoaded", fn);
          }
        }
      }

    </script>


    <link rel="stylesheet" type="text/css" href="https://www.numbeo.com/common/mmenu-light/mmenu-light.css" />
    <link rel="stylesheet" type="text/css" href="https://www.numbeo.com/common/style_mobile_b.css" />

    <title>Cost of Living</title>
  </head>

  <body>


    <nav id="header_">
      <div id="header">
        <div class="logo-and-upper-ad">
          <table class="header_table">
            <tr>
              <td style="vertical-align: top;">
                <a href="#my-menu" class="menu_link3 " style="white-space: nowrap;"><img src="https://www.numbeo.com/images/Menu1.svg" alt="" class="icon_menu3" /></a>
              </td>
              <td style="padding-left: 0.5em; padding-right: 0.5em; text-align: center;">
              </td>
              <td style="text-align: center; padding-left: 0.5em; padding-right: 0.5em; width: 100%;">
                <nav style="display: flex; flex-direction: row; vertical-align: middle; width: 100%;">
                  <form action="https://www.numbeo.com/common/dispatcher.jsp" method="get" id="menu_dispatch_form" class="dispatch_form_flex">
                    <input id="city_selector_menu_city_id" type="text" placeholder="Select City" class="city-selector-menu"...

JavaScript

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", () => {
  banner.toggleClass("alt")
})