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

What are the reasons behind professional web designers opting for absolute paths over relative paths (like for CSS, Javascript, images, etc.)?

It used to be my belief that everyone utilized relative paths, like /styles/style.css. However, I've noticed that certain renowned web designers (such as and ) prefer absolute paths (http://example.com/styles/style.css). This begs the question - why ...

Embed programming into an iframe upon its loading

I am looking to enhance the functionality of an iframe by injecting HTML and JavaScript code into it upon loading. The goal is to enable users to navigate through different links within the iframe while they are browsing. Here is what I have attempted so ...

Performing a modulo operation within a v-for loop

I'm showcasing divs in a loop and I need to assign classes based on the loop index. My goal is to have index 0 and 1 with the class col-6, then indexes 2,3,4 with the class col-4, followed by index 5 and 6 having the class col-6, and so forth. This w ...

Unexpected data output detected in Ajax Json response

I'm having trouble parsing the JSON data to HTML and encountering an undefined value. $.ajax({ type: "GET", url: "http://localhost/rest/api/kkb/detail/?key=39E62227E3294114BE8EADF3B6D2F06E&id=4", dataType: 'jsonp', cross ...

Tips on how to indicate a checkbox as selected within an Angular controller

I'm in the process of creating a form for entering new service requests, as well as displaying and editing existing ones. One part of this form includes a list of labeled check-boxes that represent different countries. When an existing request is disp ...

Steps to keep the gridlines in the chart from moving

Take a look at the example provided in the following link: Labeling the axis with alphanumeric characters. In this particular instance, the gridlines adjust dynamically based on the coordinate values. How can we modify this so that the chart remains static ...

Having trouble getting my Sequelize model to export properly

For my school project, I am developing an e-commerce website and encountering an issue with connecting my GoogleStrategy to my SQLite database. The goal is to store user data in a table, but whenever I try to call the variable in my passport-setup file, an ...

SQL stores Array Input as a static identifier 'Array'

Previously, I was able to save an object in the database. However, now I need to save each individual data in an array within a row. I attempted to use array_column to store a specific set of data in a column, but it ended up saving as the word 'Array ...

I am unable to apply CSS to style my <div> element

I've run into a snag with my coding project, specifically when attempting to style my div. Here is the code I have so far: All CSS rules are applying correctly except for the .chat rule. Can someone help me figure out what I'm doing wrong? var ...

Is there a way to align my two tables next to each other using CSS?

.page { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; } .items { float: left; } .secondItem { vertical-align: text-top; float: right; } .page-header table, th, td { border: 1px solid; display: block; background-color: ...

Does this Loop run synchronously?

Recently, I crafted this Loop to iterate through data retrieved from my CouchDB database. I am curious whether this Loop operates synchronously or if async/await is necessary for proper execution. database.view('test', 'getAllowedTracker&ap ...

Traverse through nested objects

I am currently working with JSON data containing information like uf, ivp, and others. My goal is to iterate over all the objects in order to access their properties. { "version": "1.5.0", "autor": "mindicador.cl", "fecha": "2018-10-31T13:00:00.000Z", "uf ...

How can I prevent a browser from allowing users to select an image tag?

I'm dealing with an issue on my webpage where I have an image that is inadvertently picking up mouse clicks, causing the browser to perform drag and drop actions or highlight the image when clicked. I really need to use the mousedown event for somethi ...

Transformation of an Ajax array into an associative array

Currently, I am working on creating an API using Ruby on Rails and facing a challenge with sending an array through ajax. The task seems straightforward, but the issue arises when the array is received as an associative array instead of a regular one! Es ...

Troubleshooting problems with AngularJS placeholders on Internet Explorer 9

On my partial page, I've included a placeholder like this: <input name="name" type="text" placeholder="Enter name" ng-class="{'error':form.name.$invalid}" ng-model="Name" required /> I have also set up client side validation for the ...

Learn how to bring in images using props within React and incorporate the 'import' pathway

These are the props I am passing: const people=['Eliana','Stefania','Ahmed'] { people.map(function(name, index){ return <Person item={index} name={name}/>; }) } import Eliana from '../assets/imgs/people ...

Expanding Module Scope to Just the Request (employing Require, Node.js)

Original Query The project I am currently working on is using Express to manage HTTP requests. The structure of the project is quite intricate, with multiple embedded require statements. Our main challenge lies in maintaining access to the request and re ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

The integration of Firebase Google Auth seems to encounter issues when used on the Vercel

My experience with Vercel deployment has been quite interesting. While I find that Google authentication works seamlessly on localhost, it seems to encounter an issue when deployed on Vercel. Specifically, after logging out, the currentUser variable always ...

JQuery ID Media Queries: Enhancing responsive design with targeted

Is it possible to integrate a media query into the selection of an ID using JQuery? For example: $('#idname') $('@media (max-width: 767px) { #idname }') In essence, can you target the #idname with that specified media query in JQuery ...