javascripthtmlcssnav

How to have a pop-up for a download on my navbar?


I am looking to have a pop-up when someone clicks on my download button on my navbar, but I have been having problems when trying to make it work. Here's an example website. (rubberduckvba.com) I can't link it, it gets marked as spam.

I know I am asking for someone to just write the code, but even just tips would be great =)

I have tried to make a div for each and make it hidden or visible depending on if the user clicked it, but I could not get js to recognize the div I wanted.

fetch('navbar.html').then(res => res.text()).then(text => {
  let oldelem = document.querySelector("script#navbar");
  let newelem = document.createElement("div");
  newelem.innerHTML = text;
  oldelem.parentNode.replaceChild(newelem, oldelem); // Now that the navbar is loaded, set the active link
  const currentPage = window.location.pathname.split("/").pop();
  const navLinks = document.querySelectorAll("nav a.nav-link");
  navLinks.forEach(link => {
    if (link.getAttribute("data-page") === currentPage) {
      link.classList.add("active");
    }
  });
});

marked.use({
  breaks: true
})
async function fetchReadme() {
  try {
    const response = await fetch('https://raw.githubusercontent.com/RanchoDVT/Comp-V5/dev/README.md');
    if (!response.ok) throw new Error('README not found');
    const text = await response.text();
    document.getElementById('readme-content').innerHTML = marked.parse(text);
  } catch (error) {
    console.error('Error fetching README:', error);
  }
}

async function fetchChangelog() {
  try {
    const response = await fetch('https://raw.githubusercontent.com/RanchoDVT/Comp-V5/dev/changelog.md');
    if (!response.ok) throw new Error('Changelog not found');
    const text = await response.text();
    document.getElementById('changelog-content').innerHTML = marked.parse(text);
  } catch (error) {
    console.error('Error fetching changelog:', error);
  }
}

document.addEventListener('DOMContentLoaded', () => {
  if (document.getElementById('readme-content')) {
    fetchReadme();
  }
  if (document.getElementById('changelog-content')) {
    fetchChangelog();
  }
});


// I hate js, why do I need a DOM loader check?
document.addEventListener('DOMContentLoaded', function() {

  var configForm = document.getElementById('config-form');
  var copyButton = document.getElementById('copy-button');
  var configOutput = document.getElementById('config-output');


  if (configForm) {
    configForm.addEventListener('submit', async function(event) {
      event.preventDefault();
      // Function to get the latest release version from GitHub
      async function getLatestReleaseVersion() {
        const response = await fetch('https://api.github.com/repos/RanchoDVT/Comp-V5/releases/latest', {
          method: 'GET',
          headers: {
            'User-Agent': 'JavaScript'
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        const latestTag = data.tag_name;
        return latestTag;
      }
      const formData = new FormData(event.target);
      config = `MOTOR_CONFIG
{
  FRONT_LEFT_MOTOR
  {
      PORT=${formData.get('front_left_port')}
      GEAR_RATIO=${formData.get('front_left_gear_ratio')}
      REVERSED=${formData.has('front_left_reversed')}
  }
  FRONT_RIGHT_MOTOR
  {
      PORT=${formData.get('front_right_port')}
      GEAR_RATIO=${formData.get('front_right_gear_ratio')}
      REVERSED=${formData.has('front_right_reversed')}
  }
  REAR_LEFT_MOTOR
  {
      PORT=${formData.get('rear_left_port')}
      GEAR_RATIO=${formData.get('rear_left_gear_ratio')}
      REVERSED=${formData.has('rear_left_reversed')}
  }
  REAR_RIGHT_MOTOR
  {
      PORT=${formData.get('rear_right_port')}
      GEAR_RATIO=${formData.get('rear_right_gear_ratio')}
      REVERSED=${formData.has('rear_right_reversed')}
  }
  INERTIAL
  {
      PORT=${formData.get('inertial_port')}
  }
  Rear_Bumper
  {
      PORT=${formData.get('rear_bumper_port')}
  }
  PRINTLOGO=${formData.has('print_logo')}
  LOGTOFILE=${formData.has('log_to_file')}
  MAXOPTIONSSIZE=${formData.get('max_options_size')}
  POLLINGRATE=${formData.get('polling_rate')}
  CTRLR1POLLINGRATE=${formData.get('ctrlr1_polling_rate')}
  VERSION=${await getLatestReleaseVersion()}
}`
      completeCheck = true;

      configOutput.textContent = config;

      // Show the copy button once the config is generated
      copyButton.style.display = 'inline-block';
    });
  }

  if (copyButton) {
    copyButton.addEventListener('click', function() {
      if (configOutput.textContent) {
        navigator.clipboard.writeText(configOutput.textContent)
          .then(() => {
            console.debug('Config copied to clipboard!');
            const button =
              document.querySelector('copyButton');
            copyButton.innerHTML = 'Copied! ✅';
          })
          .catch(err => {
            console.error('Error copying text (Thats one rare error!): ', err);
          });
      }
    });
  }
});
html {
  background-color: black;
  color: white;
  font-family: 'Segoe UI', Tahoma;
  scroll-behavior: smooth;
  padding-bottom: 2%;
  box-sizing: border-box;
}

nav {
  list-style: none;
  border-radius: 4px;
  overflow: hidden;
  background-color: #38444d;
}

nav li {
  float: left;
}

footer {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: #38444d;
  backdrop-filter: 8;
  color: white;
  text-align: center;
}

nav li a,
.nav-link.dropbtn {
  /* Add .nav-link.dropbtn */
  display: inline-block;
  cursor: pointer;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  border-right: 1px solid #bbb;
}

.active {
  background-color: rgb(170, 96, 36);
}

li a:hover:not(.active) {
  background-color: lightslategray;
}

nav li.dropdown {
  display: inline-block;
}

nav li:last-child a {
  border-left: 1px solid #bbb;
  border-right: none;
}

.dropdown-content {
  display: none;
  position: absolute;
  min-width: 160px;
  padding: 8px 0px;
  background-color: lightslategrey;
  border-radius: 8px;
}

.dropdown-content a {
  background-color: lightslategrey;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
  border: none;
  /* Remove borders */
}

.dropdown:hover .dropdown-content {
  display: block;
  position: absolute;
  padding: 8px 0px;
  background-color: lightslategrey;
  border-radius: 8px;
}

input {
  background: black;
  color: white;
  border: white;
  border-style: solid;
  border-width: thin
}

select {
  background: black;
  color: white;
}

.config-output {
  border-bottom: 1px solid white;
  padding-top: 10px;
  padding-bottom: 10px;
  margin-bottom: 20px;
  white-space: pre-wrap;
  /* Ensures text wraps properly (Who thought this was a good idea???)*/
  overflow-x: auto;
  /* Handles horizontal overflow (Same with this!!!)*/
}

button {
  background: black;
  color: white;
  border: white;
  border-style: solid;
  border-width: thin;
}

.form-group {
  margin-bottom: 15px;
}

a {
  color: #7bbaeb;
}
<link rel="stylesheet" href="style.css">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="main.js"></script>
<script id="navbar" src="main.js"></script>
<!-- navbar fetched from site -->
<nav>
  <li><a class="nav-link" data-page="index.html" href="index.html">Home</a></li>
  <li class="dropdown">
    <a class="nav-link" data-page="projects.html" href="projects.html">Projects</a>
    <div class="dropdown-content">
      <a target="_blank" href="https://github.com/Voidless7125/Comp-V5">Comp V3</a>
      <a target="_blank" href="https://github.com/RanchoDVT/Vex-SDK">Custom SDK</a>
      <a target="_blank" href="https://ranchodvt.github.io/Comp-V5/">This website!</a>
    </div>
  </li>
  <li class="dropdown">
    <a class="nav-link">Downloads (WIP popup)</a>
    <div class="dropdown-content">
      <a>Comp_V3 Stable</a>
      <a>Comp_V3 Pre-Release</a>
      <a>Custom SDK Stable</a>
    </div>
  </li>
  <li><a class="nav-link" data-page="features.html" href="features.html">Features</a></li>
  <li><a class="nav-link" data-page="contact.html" href="contact.html">Contact</a></li>
  <li style="float: right;"><a class="nav-link" data-page="about.html" href="about.html">About</a></li>
</nav>
<!-- end navbar -->
<div id="readme-content"></div>
<footer>Copyright © 2024 Voidless7125</footer>

Here's an example of what I am looking for when a user clicks on a download on my navbar:

what it should look like


Solution

  • To create a pop-up for your download button, you can set up a modal (a div that appears on top of the main content) that only displays when the button is clicked. Here’s a straightforward way to achieve this with JavaScript and CSS.

    Steps

    1. Create a hidden modal in HTML: This will serve as the pop-up.
    2. Write CSS for the modal: Position it so it overlays the screen when visible.
    3. Add JavaScript to handle showing and hiding the modal.

    Explanation

    1. HTML: The modal (<div id="downloadModal" class="modal">) includes a close button (<span class="close">&times;</span>) and download options. It’s hidden by default.
    2. CSS: The .modal class makes the modal cover the whole screen and .modal-content styles the actual pop-up.
    3. JavaScript: Listens for clicks on the download link to show the modal, and on the close button or outside the modal to hide it.

    Example Code

    Here's a simple implementation:

    Let me know if you run into any issues or need further help!

    // JavaScript to control the modal
    document.addEventListener('DOMContentLoaded', () => {
      const modal = document.getElementById('downloadModal');
      const downloadButton = document.querySelector('nav .dropdown .nav-link');
      const closeButton = document.querySelector('.modal .close');
    
      // Open modal when download button is clicked
      downloadButton.addEventListener('click', () => {
        modal.style.display = 'block';
      });
    
      // Close modal when the close button is clicked
      closeButton.addEventListener('click', () => {
        modal.style.display = 'none';
      });
    
      // Close modal if the user clicks outside of the modal content
      window.addEventListener('click', (event) => {
        if (event.target == modal) {
          modal.style.display = 'none';
        }
      });
    });
    /* Modal styles */
    
    .modal {
      display: none;
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
    }
    
    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
    }
    
    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }
    
    .close:hover,
    .close:focus {
      color: #000;
      text-decoration: none;
      cursor: pointer;
    }
    <!-- Add this below your navbar -->
    <div id="downloadModal" class="modal">
      <div class="modal-content">
        <span class="close">&times;</span>
        <p>Select a download:</p>
        <ul>
          <li><a href="Comp_V3_Stable.zip" download>Comp V3 Stable</a></li>
          <li><a href="Comp_V3_PreRelease.zip" download>Comp V3 Pre-Release</a></li>
          <li><a href="Custom_SDK_Stable.zip" download>Custom SDK Stable</a></li>
        </ul>
      </div>
    </div>