I need help for jQuery function

Hello Sirs! and Madams!

As I got advice that function must not be written inside the loop. Can any one please help me to do this.

This is my sample project

What I want to do is to make all the numbers on click and while clicking on numbers, they must out. can be hidden or can be removed.
I did some projects using function inside loop. But, I want to know the professional way to write this code. You can give the hints for rests, but i want to see the way of coding to make each numbers clickable.

Thank you very much in advance for your kind help.

Why don’t you first show us how you tried to make the numbers clickable? I do not see any attempt to do that yet. Once you give it a try, then let us know.

1 Like

FYI - If you are just going to put the number 0-9, then the following would be a bit more concise.

  let $nBangGameNumbersHTML = '';
  for (let num = 0; num <= 9; num++) {
    $nBangGameNumbersHTML += "<div class='numbers'>" + num + "</div>";
  }
  $(".n-b-number-placeholder").html($nBangGameNumbersHTML);
1 Like

@RandellDawson
Thank you sir, Actually I did it in my aforapple project with javascript. With jQuery I need to study a little more I think.
Thank you sir, I will let you inform my progress for this project and again will ask for help.
Regarding the project, i would keep more letters and numbers, so i used .length rather than the number. And using num varibale is more easy to understand, i will change it to num.

Making onClick function in such a situation is really tough. I did it in Javascript. But function was inside the loop. It was like this.

for (let i = 0; i < clickLetter.length; i++) {
            clickLetter[i].addEventListener("click", function(){
                wrongMessage.style.display = "none";
                sound.play();

                if (displayVal.length < clickLetter.length){
                    displayVal += clickLetter[i].innerText;
                    answerPlaceHolder.innerText = displayVal;
                }

I used this for my this aforapple project.
https://yvana.org/yvana_games/aforapple

I am doing these to understand the way. Thats why I posted this, to know Actually how can we make onclick function with these types of work.
I will try more and let you know sir.
I know this is my 3rd month of coding, and I need to to more and more practice.
Thank you very much sir.

If you will have numbers and letters, then I would do:

  const nBangGameNumbersArray = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
  $nBangGameNumbersHTML = nBangGameNumbersArray.reduce((html, char) => html += `
    <div class='numbers'>${char}</div>
  `, '');
  $(".n-b-number-placeholder").html($nBangGameNumbersHTML);

Using jQuery to add the click event listeners to the number/letter elements, you can accomplish what you want in a single line of code.

Regarding your vanilla JS code, there is nothing technically wrong with having the callback function defined as the second argument of the addEventListener method. It would just be more readable, to create a separate named function and reference the named function as the 2nd argument.

function handleClick(){
  wrongMessage.style.display = "none";
  sound.play();
  if (displayVal.length < clickLetter.length){
    displayVal += clickLetter[i].innerText;
    answerPlaceHolder.innerText = displayVal;
   }
  .
  .
  .
}

for (let i = 0; i < clickLetter.length; i++) {
  clickLetter[i].addEventListener("click", handleClick);
}

The same separate of the function would apply to the jQuery version once you create it.

2 Likes

Thank you very much sir. I am getting better and better.

@RandellDawson Thank you, I did it, I need to clear up the codes I think. I will do it

This is my simple project.
https://yvana.org/yvana_games/numberbang

and this is my script.

 <script>
     
var nBangGameNumbersArra = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ];
var nBangGameSoundsArra =  ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ];
var nbGameWrapper = document.getElementById("n-b-game-wrapper");
var myNumbers = document.getElementsByClassName("numbers");
var nBfinishMessageWrapper = document.getElementById("n-b-finish-message-place")

   // Function to randomise letter of the given words in different order 
   function shuffle(arra1) {
        var ctr = arra1.length, temp, index;
        while (ctr > 0) {                               // While there are elements in the array
        index = Math.floor(Math.random() * ctr);        // Pick a random index
        ctr--;                                          // Decrease ctr by 1
        temp = arra1[ctr];                                // And swap the last element with it
        arra1[ctr] = arra1[index];
        arra1[index] = temp;
        }
        return arra1;
    }

var nBangGameNumbersArray = shuffle(nBangGameNumbersArra);
var nBangGameSoundsArray = shuffle(nBangGameSoundsArra);

var myVal = "";

for (let i=0; i < nBangGameNumbersArray.length; i++){
    myVal +="<div class='numbers'>"+nBangGameNumbersArray[i]+"</div>";
    //var check = "<div class='numbers' onclick='removeMe(myNumbers["+[i]+"])'>"+nArray[i]+"</div>";
    nbGameWrapper.innerHTML = myVal;
}

jQuery(document).ready(function(){
    $("#n-b-game-start-btn").click(function(){
        $randomIndex = Math.floor(Math.random()*(nBangGameNumbersArray.length));
        var gameArray = nBangGameNumbersArray[$randomIndex];
        var numberSound = new Audio();
        numberSound.src = "../audios/numbers/"+nBangGameSoundsArray[$randomIndex]+".ogg";
        numberSound.play();
        $("#n-b-game-start-btn").css("display", "none");
    
        for (let j=0; j < myNumbers.length; j++){
        $(myNumbers[j]).click(function(){
                    
        if(myNumbers[j].innerText === nBangGameSoundsArray[$randomIndex]){
                    myNumbers[j].style.animation = "animatehide 1s";
                    myNumbers[j].style.transform = "scale(0)";
                    nBangGameSoundsArray.splice($randomIndex,1);
                    nBangGameNumbersArray.splice($randomIndex,1);
                    $randomIndex = Math.floor(Math.random()*(nBangGameNumbersArray.length));
                    numberSound.src = "../audios/numbers/"+nBangGameSoundsArray[$randomIndex]+".ogg";
                    numberSound.play();
            }if (nBangGameSoundsArray.length === 0){
                var clapSound = new Audio();
                clapSound.src = "../audios/clap3.wav";
                clapSound.play();
                nBfinishMessageWrapper.style.display = "block";
            }
       });
    }

        $("#play-again").click(function(){
        location.reload();
        });
    });
});
</script>

I need to clean up script. But I am in hurry to show you.
Thank you. You are my best mentor sir.

@gangalalchapain Overall, I think you did a great job on creating the game. See below for a few suggestions.

For a JavaScript game, there is no reason to do this. You should be able to play again without having to reload the page. Just think about what things would need to be “reset” and then create a function that does these things that would be called when the page loads and then again if the user clicks the “Play Again” button.

Since both of these arrays have the same elements, you only need one array. I would call it numbersArray. Then in your shuffle, you just need to provide a copy of the this array. You learned how to make a shallow copy of an array in the ES6 section of the curriculum.

A couple of non-programming suggestions:

  1. Create a delay (maybe 1 second?) between when the user clicks on the correct number and the next number is called out. Currently, it is a bit confusing because a new number is called out almost at the same time the current number is being clicked.
  2. Maybe after a correct number is clicked, a “Hurray!” or “Correct!” sound clip can be played and if an incorrect number is clicked, a “Please try again” clip is played.
  3. I recommend a visual clue to the user when an incorrect number is clicked instead of nothing happening.

@RandellDawson Thank you very much sir.

The best thing I got suggested from you is to delay the sounds, and to notify the wrong press. I wish to learn it. And, right now, I start googleing to learn it. I am really learning a lot from you and by doing some small projects. As you notify I will do it and let you know. Regarding delaying the sound, is tough for me, if you have any small hints for this sir?

Thank you very much.

Look at either setTimeout or jQuery delay method.

@RandellDawson Thank you very much sir. I did it.
Please check the game again.

https://yvana.org/yvana_games/numberbang

Just remaining is to remove window.reload and run the function. I am learning about using function more deeply again. And, will do it also.
Thank you very much for your kind support to a learner like me.

A couple of more suggestions:

#1 I know it is probably an edge case, but what if a user presses the Start button and is working through the exercise and gets distracted by something else (i.e. The user’s mother asks a question). The user comes back to the exercise but does not remember the last number that was called out.

There are a couple of options you could choose from to help this user complete the exercise:

  • Have the application repeat the call out of the number every so many seconds (i.e 3 or 5) until the correct response is clicked.
  • Have another appear only once the Start button is clicked that allows the user to click and hear the current number again.

#2 There is currently no option to stop the current game in the middle and return to the starting page.

Thank you very much sir. I will do it again and again. I am enjoying learning. thank you very much for your valuable suggestions. You really care the beginners. I am a very basic learner, So I will do it step by step.
Thank you sir.