Voidless7125
Voidless7125

Reputation: 46

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

Upvotes: 0

Views: 108

Answers (1)

Voidless7125
Voidless7125

Reputation: 46

Here's my fixing up of it:

async function getLatestRelease(repo) {
    const response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`);
    const data = await response.json();
    return data.tag_name;
}

function downloadFile(url, filename) {
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

async function showPopup(type) {
    let popupText = '';
    let downloadLink = '';

    if (type === 'dev') {
        popupText = 'Thank you for downloading Comp_V3 *dev*! This download link goes to the Github API. This is the source code. <br> <br> You will need my Custom SDK to use this. Check out my other download in the navbar.';
        downloadLink = 'https://github.com/RanchoDVT/Comp-V5/archive/refs/heads/dev.zip';
        document.getElementById('popup-title').innerText = 'Download Comp-V3 ' + type;
    } else if (type === 'stable') {
        const latestTag = await getLatestRelease('RanchoDVT/Comp-V5');
        popupText = 'Thank you for downloading Comp_V3 stable! This download link goes to the Github API. This is the source code. <br> <br> You will need my Custom SDK to use this. Check out my other download in the navbar.';
        downloadLink = `https://github.com/RanchoDVT/Comp-V5/archive/refs/tags/${latestTag}.zip`;
        document.getElementById('popup-title').innerText = 'Download Comp-V3 ' + type + ' ' + latestTag;
    } else if (type === 'sdk') {
        const latestTag = await getLatestRelease('RanchoDVT/Vex-SDK');
        popupText = 'Thank you for downloading my custom SDK. This is unofficial and in no way affiliated, endorsed, supported, or created by VEX Robotics. <br> <br> You will need this to install my Custom SDK (This) to use my Comp_V3 Program. This modifies Vex\'s robotics extension, so PLEASE don\'t go to them if you have problems with this. Please contact me. <br> <br>There is a PowerShell script for this to make it easier: ';
        popupText += '<a href="https://minhaskamal.github.io/DownGit/#/home?url=https://github.com/RanchoDVT/Vex-SDK/blob/dev/Vex-SDK.updater.ps1">Powershell download</a>';
        document.getElementById('popup-title').innerText = 'Download Custom ' + type + ' ' + latestTag;
        downloadLink = `https://github.com/RanchoDVT/Vex-SDK/archive/refs/tags/${latestTag}.zip`;
    }

    document.getElementById('popup-text').innerHTML = popupText; // Use innerHTML to render HTML content
    document.getElementById('download-link').href = downloadLink;
    document.getElementById('popup').classList.add('active');
    document.getElementById('overlay').classList.add('active');
}


function hidePopup() {
    document.getElementById('popup').classList.remove('active');
    document.getElementById('overlay').classList.remove('active');
}
.popup {
    display: none;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    border: 1px solid #ccc;
    padding: 20px;
    background-color: #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    border-radius: 8px;
}

.popup.active {
    display: block;
    background-color: black;
}

.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    background-color: black;
}

.popup-header h2 {
    margin: 0;
    font-size: 18px;
    background-color: black;
}

.download-btn, .cancel-btn {
    display: inline-block;
    margin-top: 10px;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.download-btn {
    background-color: #4CAF50;
    color: white;
    text-decoration: none;
    text-align: center;
}

.cancel-btn {
    background-color: #f44336;
    color: white;
}

.overlay {
    display: none;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999;
}

.overlay.active {
    display: block;
}
    <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</a>
            <div class="dropdown-content">
                <a onclick="showPopup('stable')">Comp_V3 Stable</a>
                <a onclick="showPopup('dev')">Comp_V3 Dev</a>
                <a onclick="showPopup('sdk')">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>

    <!-- Pop-Up Structure -->
    <div id="popup" class="popup">
        <div class="popup-header">
            <h2 id="popup-title">Download</h2>
        </div>
        <p id="popup-text"></p>
        <button class="cancel-btn" onclick="hidePopup()">Cancel</button>
        <a id="download-link" class="download-btn" href="#" download>Download</a>
    </div>
    <div id="overlay" class="overlay" onclick="hidePopup()"></div>

Upvotes: 1

Related Questions