Javascript downloadable content available for download

<div class="center"data-role="content" id="content"  >
        <a href="#flappy" data-transition="slide" >Avoid Becoming a Terrorist</a>
        </div>

    <div id="flappy" >
    <center>
    <div id="page">
            <div data-role="header">
            <h1 style="color: white; font-size: 20px;">Avoid Becoming a Terrorist</h1>
            <a data-icon="home" data-rel="back" style="margin-top:2px; background-color: white;">....</a>
        </div>

        <div id="frame" onload="check2()">
        <script>
        function check2(){
        $.get(/flappy.html)
    .done(function() { 
    alert("you have it");
                <p style="color: white; margin-top: 30px;">Avoid becoming a terrorist is a game where you must guide a plane through buildings without crashing. Be careful to not cause any destruction and complete the mission successfully.<br> Controls:<br>Hold the screen down to go up, let go to go down. Avoid collisions with buildings to survive.</p>
        <a href="flappy.html" data-transition="pop" rel="external"><img src="images/play.png" width="320px" height="320px"></img></a>

    }).fail(function() { 
    alert("Download it now!");
    })
    }
    </script>
    
        </div>
        </div>
        </center>
    </div>

This code snippet is designed for a gaming website, offering users the option to play or download a game titled "Avoid Becoming a Terrorist". The script checks for the existence of the game file and provides appropriate actions based on its availability. Hope this helps in your website development!

Happy coding! :)

Answer №1

The onload event can only be utilized on the document(body) itself, frames, images, and scripts.

If the file is present, users should have the option to play the game; otherwise, provide a button for them to download it.

You can verify the existence of the file using jQuery's ajax success & error methods:

$(document).ready(function(){
    $.ajax({
        url:'path/to/game.html',
        type:'HEAD',
        success: function() {
            alert('Game exists, add some code.')
        },
        error: function() {
            alert('Download Game !')
        }
    })
})

You can also use Vanilla JavaScript to check if the file exists

function gameExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

if(gameExists('path/to/game.html')) {
    alert('Game exists, add some code.');
} else {
    alert('Download Game !');
}

If you prefer not to use ajax, you can utilize PHP to determine file existence and then embed a javascript variable in the code.

<script type="text/javascript">
    var gameExists = <?php echo file_exists($fileName) ? true : false;?>
</script>

To append HTML content to the frame container, you can employ jQuery Append()

$('#frame').append('<a href="#/download">Download</a>');

Answer №2

Unclear about your request:

If the file exists, provide an option to play the game. If not, offer a button for them to download it.

But what will they be downloading if there is no file available? Nonetheless, you can initiate a download in browsers that support the use of the download attribute for link elements. Currently, this functionality is compatible with Chrome and possibly Firefox.

Referencing this answer,

var myLink = document.createElement('a');
myLink.href = 'path_to_file_you_want_to_give_them.extension';
myLink.download = 'whatever_you_want_to_call_the_file_that_they_get.extension';
document.body.appendChild(link);
link.click();

In essence, this code generates a link leading to the desired file for them to download, allows customization of the downloaded file name, appends the link to the DOM, and triggers a click event using jQuery's function to ensure initiation of the download process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error with constructor argument in NestJS validator

I've been attempting to implement the nest validator following the example in the 'pipes' document (https://docs.nestjs.com/pipes) under the "Object schema validation" section. I'm specifically working with the Joi example, which is fun ...

Transform date format using VueJS in JavaScript

I need to convert a date format from 19 Oct 2017 to 20171019. Is there a way to do this quickly? I am using FlatPickr in VueJs. Here is the code snippet for reference: import flatPickr from 'vue-flatpickr-component'; import 'flatpickr/dist/ ...

"Utilize AJAX to submit the value of the text box input from a jQuery slider when the Submit Button

Whenever I adjust the sliders, the value is shown in an input textbox. However, when I move the slider and check the values echoed from the textboxes on another PHP page, they are always displaying as 0. Even after clicking the submit button, it still echo ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...

Error: Attempting to retrieve a refresh token from the Google API resulted in an Uncaught ReferenceError, as the

I am currently working on obtaining a refresh token once a user authorizes with Google in order to prevent the need for re-authorization. After studying Google's documentation, I learned that setting the access type to offline is necessary. Now, I am ...

Utilizing util.format to enclose every string within an array with double quotation marks

Currently .. var utility = require("utility"); var carsInput = 'toyota,chevrolet'; var cars = carsInput.split(','); var queryString = utility.format('Cars: [%s]', cars); console.log(queryString); // Cars: [toyota,chevrolet] ...

Adjust picture dimensions when the window changes (using jQuery)

Hey there, I'm in need of some help resizing images on my webpage. I want the images to adjust their size when the page loads or when the browser is resized. The images can be either portrait or landscape, and they will be contained within a div that ...

What are the pros and cons of using a piped connection for Puppeteer instead of a websocket?

When it comes to connecting Puppeteer to the browser, you have two options: using a websocket (default) or a pipe. puppeteer.launch({ pipe: true }); What distinguishes these approaches? What are the benefits and drawbacks of each method? How do I know wh ...

Is there an alternative method to retrieve the client's user agent if getStaticProps and getServerSideProps cannot be used together?

I am currently facing a challenge with the website I'm working on as it lacks a responsive design. This means that the view I display is dependent on the user agent of the client. In order to achieve this, I have been using getServerSideProps to deter ...

developing versatile paths with Node.js

app.js // Including Routes require("./routes")(app); router folder index.js module.exports = function (app) { app.use("/", require("./all_routes")); } all_routes.js var express = require("express"); var route ...

I'm having trouble understanding why my Javascript validation suddenly stopped functioning. Can anyone assist me in troubleshooting this issue?

I have been working on this webpage for a school project for a few days, and it was running smoothly until about 10 minutes ago. The only change I made was adding an extra JavaScript validation. Now, when I try to register by clicking the "register" butt ...

Ways to identify an element within a webpage

I'm currently working on creating a chrome extension that can detect the presence of specific elements on a webpage. The goal is to have this extension automatically run every time a new page is opened and display a popup message if the element is fou ...

Oops! Looks like there was an issue with defining Angular in AngularJS

I am encountering issues while attempting to launch my Angular application. When using npm install, I encountered the following error: ReferenceError: angular is not defined at Object.<anonymous> (C:\Users\GrupoBECM18\Documents&bs ...

Using AJAX to populate a dropdown menu in a CodeIgniter application

I'm having an issue with using AJAX to populate a dropdown option. Here is the JavaScript code I am using: <script type="text/javascript"> $(document).ready(function(){ $("#sepatu").click(function(e){ e.preventDefault() ...

Creating a secure authentication system with Parse for password recovery and website logins

Our organization has chosen to utilize a Parse backend for managing user accounts, and I am tasked with creating web pages for functionalities like password reset that will seamlessly integrate with our mobile applications. It has been some time since I ha ...

The issue with displaying inline block is that the divs are not appearing side by side on the

Two of my div elements, namely form-panel and data-panel, are currently not aligned on the same line. How can I use display:inline-block to align them in a single line? Please review the code provided below. I have already used display:inline-block on both ...

Creating interactive dropdown menus with PHP and Catalyst using Jquery

Currently, I am working on incorporating cascading dropdown menus into a catalyst web app. The main goal is to allow users to select a database table from the first dropdown menu and have the columns of that table populate the second dropdown menu. To achi ...

AngularJS's support for html5mode on GitHub pages is now available

Is it feasible for GitHub pages to accommodate AngularJS in html5mode? I came across a source online suggesting that it can be done with a fallback page for 404 errors. However, this solution seems flawed as it may result in multiple 404 errors, which wou ...

Bringing in data from <script> to use in <script setup>

To ensure unique ids for instances of a Vue component, I am using a simple generator to enumerate them. Typically, I would initialize the generator outside of the setup function like this: const idGen = generateIds("component:my-component"); export defaul ...

Creating dynamic forms with JQuery and ReactJS

I have been tasked with creating a form-builder that will be integrated into an application. My role is to focus on designing the front-end using ReactJS. The client’s requirements are very similar to the features of the "jQuery Form-Builder," so I decid ...