Home > Mobile >  How to change dropdown background color on certain pages?
How to change dropdown background color on certain pages?

Time:09-16

I have a webpage with a header with several dropdown menus in it. What I would like is to have certain pages, when CLICKED from any of the dropdown items to have the background color of the dropdown stay that color? Any page clicked on the image below lets users know that they are still in that HTML section.

enter image description here

My current code, do I need 2 'dropdowns' in the CSS or can I add a background inline and where would I add it to the code? So any page that falls in the APPLICATION PAGE dropdown, the APPICATION dropdown background is grey, and any page that falls in the TECHNICAL PAGE dropdown, the TECHNICAL dropdown background is grey?

<div >
<button >APPLICATION PAGE
  <i ></i>
</button>
<div >
  <a href="../page">PAGE 1</a>
  <a href="../page2.htm">PAGE 2</a>
  <a href="../page3.htm">PAGE 3</a>
  <a href="../page4.htm">PAGE 4</a>
  <a href="../page5.htm">PAGE 5</a>
  <a href="../page6.htm">PAGE 6</a> 
  <a href="../page7.htm">PAGE 7</a> 
</div>
TECHNICAL PAGE PAGE 22 PAGE 23 PAGE 25 PAGE 26 PAGE 27

Would it be easier to change the background of the buttons with an inline style?

CodePudding user response:

There is, as yet, no way to implement this functionality using just CSS; though Selectors module (Level 4) does define the :local-link pseudo-class, which:

…allows authors to style hyperlinks based on the users[sic] current location within a site. It represents an element that is the source anchor of a hyperlink whose target’s absolute URL matches the element’s own document URL. If the hyperlink’s target includes a fragment URL, then the fragment URL of the current URL must also match… (https://www.w3.org/TR/selectors-4/#the-local-link-pseudo)

Until then, unfortunately, we're left using JavaScript:

// Simple helper utilities in order to avoid repetitive typing where possible:
const D = document,
  // an alias of document.querySelector and Element.querySelector, depending
  // upon the supplied 'ctx' (if any); defaults to document:
  get = (sel, ctx = D) => ctx.querySelector(sel),
  // an alias of querySelectorAll(), as above defaults to document.querySelectorAll
  // but will implement Element.querySelectorAll() if the 'ctx' argument is
  // provided; returns the iterable NodeList as an Array of Nodes in order to
  // use Array methods (Array.prototype.filter(), Array.prototype.map(), etc):
  getAll = (sel, ctx = D) => [...ctx.querySelectorAll(sel)],
  // an alias of Document.createElement(), which allows properties to be
  // assigned to the created element (such as 'textContent', 'className', 'innerHTML'...):
  create = (tag, props) => Object.assign(D.createElement(tag), props),
  // not used a lot, but if multiple elements are to be added to the DOM, the
  // document-fragment can hold the elements and then the fragment can be appended
  // to the recipient parent-node to minimise (relatively expensive) redraws in the browser:
  fragment = () => D.createDocumentFragment();

// here we retrieve the element that will link to the current to the page,
// and set its href property to the absolute URL of the current document:
get('a#currentPage').href = document.location.href;

// here we're testing if the browser supports (or claims support) for
// the 'a:local-link' selector, by combining CSS.supports() with the
// CSS supports selector() function. If the browser claims support the
// CSS.supports() method returns a Boolean true, if the browser reports
// that the selector is unsupported then a Boolean false is returned.
// Here we're inverting the return value to convert the probable-negative
// into a positive (to execute the code within the if block:
if (!CSS.supports("selector(a:local-link))")) {
  // caching the document location:
  let currentPage = window.location.href;
  
  // retrieving all <a> elements in the document, and iterative over those
  // elements with Array.prototype.forEach():
  getAll('a').forEach(
    // using an Arrow function to pass a reference to the current Element into
    // the arrow function, in which we toggle the 'localLink' class on the
    // element. If the assessment returns true (or truthy) the class-name is
    // added (if not already present) if the returns false (or falsey) then
    // the class-name is removed (if present).
    // So here we're adding the 'localLink' class to all elements whose
    // href property starts with the URL for the current page (this means that
    // elements linking within the current page also receive the class):
    (el) => el.classList.toggle('localLink', el.href.startsWith(currentPage))
  )
// in this example we don't use an 'else' because the else implies the browser supports
// a:local-link (or there's a browser bug), so we can rely on CSS to style the
// relevant elements.
}
/* simple reset to have all sizes calculated to include padding and borders, reducing
   browser-default margin and padding to reduce cross-browser layout differences: */
*,
::before,
::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* because I prefer smooth-scrolling */
html {
  scroll-behavior: smooth;
}

body {
  font-family: Ubuntu, Calibri, Helvetica, system-ui;
  font-size: 1em;
}

main {
  display: grid;
  grid-template-columns: 15rem 1fr;
  gap: 0.5em;
  inline-size: clamp(20rem, 70vw, 1200px);
  margin-inline: auto;
}

nav,
section {
  padding-block: 1em;
}

footer {
  grid-column: 1 / -1;
}

ol,
li {
  list-style-type: none;
}

ol {
  display: grid;
  gap: 0.5em;
}

/* styling all <p> elements which are not
   the first-child, or last-child, of their
   parent element: */
p:not(:first-child, :last-child) {
  margin-block: 1em;
}

em {
  font-style: italic;
}


nav a {
  display: block;
}

/* relevant stuff */

/* selecting all <a> elements which match either of
   the enclosed pseudo-classes: */
a:is(:link, :visited) {
  color: hsl(200deg 80% 60%);
  transition: color 0.3s ease-in;
}

/* :local-link is currently unsupported (to the extent that
   there isn't even a "can I use" entry); it's defined in
   the Selectors module, level 4. Here we select all <a>
   elements that match either the :local-link pseudo-class
   or which have the 'localLink' class (or both, as these
   selectors are not exclusive of each other): */
a:is(.localLink, :local-link) {
  color: hsl(36deg 100% 50%);
}

/* selecting all <a> elements matching any, or more than one,
   of the pseudo-classes: */
a:is(:hover, :active, :focus, :focus-visible) {
  color: hsla(0 100% 50%);
  outline-offset: 0.3em;
}
<main>
  <nav>
    <ol>
      <!-- The link below is the link to the current page for demo purposes;
           the href will be added via JavaScript, so that the demo is (as far
           as possible) transferable to other locations: -->
      <li><a id="currentPage" href="#">This very page!</a></li>
      <!-- the link below links to an element on the same page document via
           the fragment-identifier: -->
      <li><a href="#footer">The footer content</a></li>
      <li><a href="https://developer.mozilla.org/">MDN</a></li>
      <li><a href="https://stackoverflow.com">Stack Overflow</a></li>
      <li><a href="https://api.jquery.com/">jQuery API</a></li>
      <li><a href="https://developers.google.com">Google Developers</a></li>
      <li><a href="https://web.dev/learn/">Learning resource, often promoted by Google devs/employees</a></li>
      <li><a href="https://openprops.style">Adam Argyle's "open props"</a></li>
      <li><a href="https://css-tricks.com/">CSS Tricks</a></li>
      <li><a href="https://alistapart.com/">A classic resource, A List Apart</a></li>
      <li><a href="https://smashingmagazine.com">Smashing Magazine</a></li>
      <li><a href="https://rachelandrew.co.uk/">Rachel Andrew</a></li>
    </ol>
  </nav>
  <section>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem, incidunt quis repellat facere. Dolores doloribus blanditiis, quaerat consectetur explicabo veritatis corporis possimus ut debitis ad iure incidunt aliquid porro deserunt eligendi impedit,
      facere assumenda sapiente quasi odit? Dolore aut, placeat saepe.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident, exercitationem, delectus nobis quidem consectetur molestias cupiditate.</p>
  </section>
  <footer id="footer">
    <p>&copy; Absolutely <em>no</em> copyright is claimed in any part of this ridiculously simple demo; if it's of use in any way then &ndash; <em>please</em> &ndash; help yourselves.</p>
  </footer>
</main>

JS Fiddle demo.

References:

Bibliography:

CodePudding user response:

 <style>
        .dropbtn {
            background-color: #4CAF50;
            color: white;
            padding: 16px;
            font-size: 16px;
            border: none;
            cursor: pointer;
        }
  
        .dropdown {
            position: relative;
            display: inline-block;
        }
  
        .dropdown-content {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 160px;
            box-shadow: 0px 8px 16px 
                0px rgba(0, 0, 0, 0.2);
            z-index: 1;
        }
  
        .dropdown-content a {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
        }
  
        .dropdown-content a:hover {
            background-color: #f1f1f1
        }
  
        .dropdown:hover .dropdown-content {
            display: block;
        }
  
        .dropdown:hover .dropbtn {
            background-color: #3e8e41;
        }
    </style>
<body>
    <center>
        <h1 style="color: green">
           
        </h1>
          
        <div >
            <button >
                Country Flags
            </button>
              
            <div >
                <a href="https://freepngimg.com/thumb/light/2-2-light-free-download-png.png">
                    <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200630132503/iflag.jpg"
                    width="20" height="15"> India</a>
  
                <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/640px-PNG_transparency_demonstration_1.png">
                    <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200630132504/uflag.jpg"
                    width="20" height="15"> USA</a>
                <a href="#">
                    <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200630132502/eflag.jpg"
                    width="20" height="15"> England</a>
                <a href="#">
                    <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200630132500/bflag.jpg"
                    width="20" height="15"> Brazil</a>
            </div>
        </div>
    </center>
</body>

This example can help with switching between bg imgs.

  •  Tags:  
  • html
  • Related