skip to Main Content

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 a example website. (rubberduckvba. com) I cant 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 if the user clicked it, but I could not get js to recognise 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 a example of what I am looking for when a user clicks on a download on my navbar.

2

Answers


  1. Chosen as BEST ANSWER

    Here's my fixing up of it: main.js

    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');
    }
    

    the navbar:

        <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>
    

    and the css:

    .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;
    }
    

  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search