In JavaScript, alert a message once all images have been clicked

I'm encountering a small issue with my javascript code. I am developing a game for a school project where the objective is to click (remove) fish using a fishing rod. However, the game does not have an end condition set up, so players cannot win. Below you will find the complete HTML and JavaScript code for reference. Additionally, there is a link to a jsbin demonstration of the game with all CSS, HTML, and JavaScript elements combined for easier understanding. Does anyone know how to implement a win condition that stops the game when all fish are clicked (removed) and triggers an alert saying "You Won!"?

Thank you

https://jsbin.com/fihebiwiqi/edit?html,css,output

<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>

    <link rel="stylesheet" type="text/css" href="css1.css">
    </head>

    <body  background="https://guideinparadise.files.wordpress.com/2013/01/down-below2.jpg">
      <h1>Fishing Game</h1>
      <img id="fishingrod" src ="https://pixabay.com/static/uploads/photo/2014/03/24/17/07/fishing-rod-295096_960_720.png">
    <p>Seconds:</p>
      <p id="clock"></p> 
        <form action="html.html">
        <input id='level1' type="submit" value="Level 1">
    </form> 
        <form action="html2.html">
        <input id='level2' type="submit" value="Level 2">
    </form> 
        <form action="html3.html">
        <input id='level3' type="submit" value="Level 3">
    </form> 
        <form action="html4.html">
        <input id='level4' type="submit" value="Level 4">
    </form> 
    <form action="html5.html">
        <input id='level5' type="submit" value="Bonus Level">
    </form> 


        <script> 
      document.body.style.cursor = 'none'; // remove cursor
    $(document).mousemove(function (e) { //mouse moves over image
       $('#fishingrod').offset({  
            left: e.pageX + -190,  
            top: e.pageY + -110
        });
    });

      var b = 1; 
      for (var i= 0; i<5;i++){ // create loop to display 5 fish images
      fish(b);
      }
    function position(element) {
        var x = document.body.offsetHeight-element.clientHeight;
        var y = document.body.offsetWidth-element.clientWidth;
        var Xcoord = Math.floor(Math.random()*1*x + 300);
        var Ycoord = Math.floor(Math.random()*y + 50);

        return [Xcoord,Ycoord]; 


    }

    function fish() {

        var img = document.createElement('img'); 
        img.className = 'fish2';
        img.setAttribute("style", "position:fixed;");
        img.setAttribute("src", "http://res.freestockphotos.biz/pictures/16/16806-illustration-of-a-cartoon-blue-fish-pv.png"); 
        img.setAttribute("width", "200");
        document.body.appendChild(img);
        var xy = position(img); 
        img.style.top = xy[0] + 'px'; 
        img.style.left = xy[1] + 'px'; 
       $(img).click(function(){ $(this).remove();}); 

    }
      myTimer = setInterval(myCounter, 1000); 
      var seconds = 0; 
      function myCounter() {
        document.getElementById("clock").innerHTML = ++seconds; 
    }
        </script>

    </body>
    </html>

Answer №1

There is a function fisk(b); that you have defined, but the argument is never utilized...
The variable myTimer does not have a var declaration and should be initialized at the beginning of the code.

Initialize a new variable:

var fishes = 5;

Use this variable in your for loop (instead of hardcoding 5)
Then update this line

$(img).click(function(){ $(this).remove();});
to:

$(img).click(function(){

     fishes -= 1;
     $(this).remove();

     if(!fishes) {
        clearInterval(myTimer);
        alert("It took you "+ seconds +" seconds.");
     }

});

Answer №2

To keep track of counts, you have the option to use a global counter or incorporate a counter within the fisk() function (functions can act as objects).

In the example below, we demonstrate how to integrate a variable into the function. If you prefer a global variable instead, simply substitute fisk.counter with fisk_counter - just remember to initialize var fisk_counter = 0 outside of your function.

I've trimmed down the content in the fisk() function for illustrative purposes, allowing you to observe the modifications made.

function fisk() { //creating a function
    fisk.counter += 1; // increase counter
    var img = document.createElement('img'); // creates an element 
    $(img).click(function(){
        $(this).remove();
        fisk.counter -= 1; // decrease counter
        if( fisk.counter === 0 ) { // checks if all fish have been removed
            // GAME WON =)
        }
    });
}
fisk.counter = 0; // Include counter in the function

Answer №3

By removing the fishes from the DOM, you eliminate any chance of clicking on them again after they've been taken out. To keep track of the clicks, consider storing the count in a closure variable. Here's a suggestion:

var totalFish = 5; // Use this value in your loop that invokes the fisk() function

function winGame() {
   // Add code here to indicate that you've won the game
}

(function() {
   var removedCount = 0;
   function fisk() {
      // Set up your code;
      $(img).click(function() {
         removedCount++;
         if(removedCount === totalFish) {
            winGame();
         } else {
            $(this).remove();
         }
      });
   }
}());

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

Rails: Utilizing AJAX to dynamically populate Bootstrap dropdown menus

In the setup I have, there is a dropdown responsible for displaying notifications. <li class="notifications dropdown"> <a class="dropdown-toggle" id="dLabel" role="button" data-remote="true" data-toggle="dropdown" data-target="#" href="/notifi ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

Failed to execute test suite in React and Jest framework

While working on updates for our existing project, I encountered an error that is causing some of the tests to fail: FAIL src/components/changelog/__test__/ChangeLogOverView.test.tsx ● Test suite failed to run TypeError: Cannot create property & ...

What steps can be taken to avoid an abundance of JS event handlers in React?

Issue A problem arises when an application needs to determine the inner size of the window. The recommended React pattern involves registering an event listener using a one-time effect hook. Despite appearing to add the event listener only once, multiple ...

The Controller is encountering an empty child array when attempting to JSON.stringify it

After examining numerous similar questions, I am uncertain about what sets my configuration apart. I've experimented with various ajax data variations and JSON formatting methods, but the current approach seems to be the closest match. This issue is ...

JS-generated elements do not automatically wrap to the next line

For my first project, I've been working on a to-do list and encountered an issue. When I create a new div with user input, I expect it to start on a new line but it remains stuck on the same line. Can anyone point out where I might have gone wrong? I ...

Print out two forms separately using HTML5

I'm currently tackling a project that condenses all content onto one convenient page, housing two forms. Despite my efforts, I have yet to find a successful solution. My goal is to print the Sales person form first, followed by the Customers section. ...

Modifying the appearance and behavior of an element dynamically as the page is being loaded using AngularJS

Struggling with a challenge for two days now, I have attempted to implement a panel-box using bootstrap and AngularJS. Within the confines of a controller, my code looks like this: <div id="menu2a"> <div class="panel list-group"> <div ...

Setting the background color in a grid column of Struts jQuery Grid is a simple and effective way to customize

Recently, I have started exploring Struts and jquery. My goal is to change the background color of a grid column using the struts2-jquery API. I attempted to achieve this using the effectOptions attribute, however, it did not produce the desired result. ...

Adjusting a parameter according to the width of the browser window?

Using Masonry, I have implemented code that adjusts the columnWidth to 320 when the screen or browser window width is less than 1035px. When the width exceeds 1035px, the columnWidth should be 240. However, the current code keeps the columnWidth at 320 re ...

The JSON data sent from the primary Electron process is arriving as undefined in the renderer

Currently delving into an Electron project to explore the technology. It's been a captivating and enjoyable experience so far as I work on creating a basic home controller for my IoT devices. However, I've encountered a minor issue. In my main.js ...

React - utilize a variable as the value for an HTML element and update it whenever the variable undergoes a change

I'm on a mission to accomplish the following tasks: 1.) Initialize a variable called X with some text content. 2.) Render an HTML paragraph element that displays the text from variable X. 3.) Include an HTML Input field for users to modify the content ...

Streamline the process of implementing a sticky menu scroll function with jQuery

I have a horizontal navigation on my single page website that turns into a sticky navigation at a specific point. I have created a scroll-to navigation that functions like this: $(document).ready(function () { $("#button0").click(function() { ...

Why does the div inside the tbody element get automatically shifted outside of the tbody during rendering?

Below is a snippet of my code: <body> <table> <tbody> <div>test</div> </tbody> </table> </body> Upon executing the code mentioned above, it transformed automatically in ...

What steps do I need to take to successfully implement a $.fn. function that runs automatically when it is called?

I'm struggling with the following piece of code: function init() { var $contentButtonPanel: JQuery = $('#content-button-panel') $contentButtonPanel .find('.arbo .toggle, .collapsible-list li:has(ul) > ...

What is the best method for positioning two forms in a vertical arrangement?

I'm looking to integrate a Login form in HTML within my C# project. Here's what I have so far: However, as you can see, the layout is not very aesthetically pleasing. I'm struggling to align the elements in a more visually appealing way. My ...

Is it possible to adjust the size of a p5.js canvas within a bootstrap Div container?

I am attempting to incorporate a p5js canvas into a bootstrap grid structure. My goal is to have each div within the grid contain its own unique p5js canvas, which should adjust in size when the browser is resized. Below is my bootstrap grid setup, showca ...

One column stretching all the way to the window's edge while the other column stays contained within its container

Looking to design a two-column layout where the left column takes up 40% of the container and aligns with it, while the right column expands all the way to the window edge. I managed to achieve this using position:absolute, but I'm curious if there&ap ...

css - align the arrow to the right in a dropdown

I recently started using a Bootstrap dashboard template created by Creative Tim. I am attempting to incorporate a dropdown list into a table cell, following the standard Bootstrap format: <div class="btn-group"> <button type="button" class="b ...

Issue with showing multiple images on HTML page

I'm currently working on enhancing my webpage by enabling the upload of multiple images. However, I'm facing challenges in figuring out how to obtain a valid URL for the image source and to verify if the correct number of files have been uploaded ...