Misconception about the usage of jQuery's .each() function clarified with an illustrative example

Problem Description (See Fiddle):

When clicking on the red boxes, they transform into kittens and display an alert with the current value of i. Clicking on a large fading kitten will reset everything.

I am puzzled as to why alert(i) is triggering multiple times, increasing exponentially with each pass after the first click. I am also unsure of how to prevent this behavior. Initially, I thought it was due to creating new DOM elements, but since I'm only changing the img source, I am not certain.

If you find any issues or inefficiencies in my code, please do point them out to me. I welcome suggestions on more elegant solutions.

Code:

cats = [
    "http://placekitten.com/g/121/121",
    "http://placekitten.com/g/122/122",
    "http://placekitten.com/g/123/123",
    "http://placekitten.com/g/124/124",
    "http://placekitten.com/g/125/125",
    "http://placekitten.com/g/126/126",
    "http://placekitten.com/g/127/127",
    "http://placekitten.com/g/128/128",
    "http://placekitten.com/g/129/129",
    "http://placekitten.com/g/130/130"
];
count = 0;

function getRandomCats() {
    var kitties = [];
    for(i = 0; i < 3; i++) {
        rand = Math.floor(Math.random() * (9 - 0 + 1)) + 0;
        kitties[i] = cats[rand];
    }
    meow(kitties);
}

function meow(kitties) {
    $('.cats').each(function(i) {
        $(this).mousedown(function() {
            alert(i); //debug
            $('div.front img', this).attr('src', kitties[i]);
            $(this).css({
                'transform': 'rotateY(180deg)',
                '-webkit-transform': 'rotateY(180deg)',
                'transition': 'transform 500ms ease-in-out',
                '-webkit-transition': '-webkit-transform 500ms ease-in-out'
            });
            this.flipped = 1, this.locked;
            if (this.flipped && !this.locked) {
                this.locked = 1;
                count++;
                if (count > 2) {
                    $('#newCat').fadeIn();
                }
            }
        })
    });
}

var clicked = 0;
$('#newCat').mousedown(function() {
    if (clicked == 0) {
        clicked = 1;
        $(this).stop(true).fadeOut();
        $('.cats').fadeOut(1000, function() {
            this.flipped = 0, this.locked = 0, count = 0;
            $(this).hide().css({
                'transform': 'rotateY(0deg)',
                '-webkit-transform': 'rotateY(0deg)'
            });
            getRandomCats();
            $(this).fadeIn();
        });
    }
    setTimeout(function(){clicked = 0;}, 1000);
});

getRandomCats();

Answer №1

To prevent overwriting previously bound functions with the mousedown statement, simply include the following code:

$(this).unbind("mousedown");

This should be placed before the $(this).mousedown binding statement.

In regards to elegance, it is recommended to segment your code into multiple functions. Excessive indentation beyond 2 levels can make the code harder to read. Avoid indenting to 5 or more levels for optimal readability.

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

Styling X and Y axis font color in charts using JavaFX 2.x CSS

Is there a way to change the font color of both X and Y axes? In my search through the css reference for fonts, I only found properties like font-size, font-style, and font-weight. font-size, font-style and font-weight I attempted to use -fx-font-color ...

What are the best methods for testing a function containing multiple conditional statements?

I have a complex function that I want to showcase here, it's quite simple but for some reason, I'm struggling with writing unit tests for it. I don't need the exact unit test implementation, just a general approach or tips on how to handle i ...

The plugin that simplifies adding and removing form fields in jQuery

I am in search of a quality plugin that can easily add or remove a set of form fields on a webpage. I came across this one , which seems to fit my requirements. However, I am exploring other options to see if there is an even better plugin available. Ther ...

Tips for updating the border color of a button:

Struggling to alter the border color of a button Attempting borderColor attribute proved futile: borderColor: '#FFFFFF' Anticipated result Code snippet: headerBtn: { backgroundColor: 'black', fontSize: '16px', f ...

Position the image slider uniformly at the bottom using CSS (utilizing the Slick Carousel library)

I am utilizing the slick carousel library to create a unique and elegant slider. However, when using images with varying heights, I am encountering issues in aligning the images at the same bottom: https://i.stack.imgur.com/ab5s3.png Here is my code snip ...

What is the method for formatting within the <textarea> element?

While working on developing a comment system, I recently made the discovery that text areas cannot be formatted to retain paragraphs, line breaks, etc. This was particularly noticeable when comparing sites like StackOverflow, which uses a text editor inste ...

How to disable JQuery accordion functionality?

Is there a method to effortlessly toggle between displaying content with an accordion format and without it? Essentially, can the styles and behaviors applied to my divs be reversed back to their original state before being "accordionized"? ...

After using promise.all, I successfully obtained an array of links. Now, how do I calculate the total number of links in the array?

function verifyAndTallyURLs(linksArray) { let validations = linksArray.map((link) =>{ return fetch(link) .then((response) => { return { webpageURL: response.url, status: response.status, ...

Step-by-step guide for implementing LoadGo animation with HTML

I'm in the process of loading my logo on my website's homepage. I found a LoadGo animation that I want to use, which can be downloaded Here Currently, the logo is set to load when a button is clicked. However, I would like it to load automatical ...

Using GeoJson in Leaflet for map display

As I develop an Angular application with Leaflet, my goal is to showcase numerous municipalities within my country: https://i.sstatic.net/9cuSW.png In order to enhance navigation efficiency, I decided to divide my JSON file into multiple files and store ...

Utilizing the power of Node.js with Oracle seamlessly, without the need for the Oracle Instant

Currently, I am working on testing the connectivity to our Oracle databases. Recently, I came across node-oracledb, a tool released by Oracle that aims to simplify this process. However, one major hurdle is the requirement of having the Oracle Instant Clie ...

Mastering Vue 3: Simplifying a reactive array of objects while maintaining reactivity

Struggling with maintaining reactivity in Vue 3 when flattening a nested array of objects. Unfortunately, my attempts result in crashing and browser hang-ups. In my Vue 3 component, I have an array structured as a list of objects: this.grouped = [ ...

What is the best way to incorporate link tags into text in AngularJS?

I'm struggling with making links within strings clickable in Angular. Can anyone provide guidance on how to accomplish this? One of the string examples from my JSON data is: "I’m hosting #AFF Catwalk Show @Bullring on 27th Sept with @BillieFaiers. ...

How can I use jQuery to locate all elements that match a specific style within the DOM?

Similar Question: How can I target hidden elements? Selecting multiple elements with CSS display:none property <div class="container"> <p style="display:none">I am hidden</p> <p>I am visible</p> <p>I am also ...

revealing the hidden message on the back of the card

I have been working on creating flipping cards for my website using CSS, but I am facing an issue. Even after styling my cards as per the provided CSS code, I am unable to make them flip when I hover my mouse over them. .row { padding-top: 25px; } .c ...

Exploring the process of retrieving parameters within a component using React Router DOM version 4

I am struggling with the following code: <BrowserRouter> <Route path="/(:filter)?" component={App} /> </BrowserRouter> In previous versions of React Router, wasn't the filter param or '' on the root supposed to be in ...

I am facing an issue with effectively passing properties from a parent state to its child component

In the Login component, I set the authentication state using the token as false initially. After a successful login, the token is changed to true. function Login() { const [user, setUser] = useState({ name: '', email: '' }); const [ ...

Utilize the cube function in JavaScript to zoom in on the cube automatically when the page loads

I have the code below. When the page loads, I would like the cube to zoom out and stop. I am new to 3js and have no idea how to achieve this. I want the cube to start small and then grow into a larger cube before stopping. <script> //var re ...

Performing synchronous POST requests to manipulate data in a SQL database using AJAX

My goal is to send synchronous calls to a page that will handle the SQL insertion of words I am posting. However, due to the large number of chunks and the synchronous nature of SQL, I want each AJAX call to be processed one after another. for (chunk = 1; ...

Passing variables to the ajax.done() function from within a loop - what you need to know

How can I pass a variable to the .done() method of an ajax call that is inside a loop? The code snippet below shows my initial attempt: <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </ ...