Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 198875
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T16:58:31+00:00 2026-05-11T16:58:31+00:00

Have been struggling with Javascript closure for a while trying to wrap brain around

  • 0

Have been struggling with Javascript closure for a while trying to wrap brain around function scopes, but I think they’re wrapping around me instead. I’ve looked at a number of posts (Nyman’s was the most helpful) but obviously still don’t get it. Trying to run a loop over the hover method in jQuery. Need hover functions to ultimate trigger more than one action each, but would be happy to get them working with a single image swap each for now.

$(document).ready(function() {

    imageSource = []; 
    imageSource[0] = 'images/img0.png'  //load 0 position with "empty" png
    imgArea = [];

    for (var i=1; i<11; i++) {

        (function( ){  //anonymous function for scope

            imageSource[i] = 'images/img' + i + '.png';
            imgArea[i] = '#areamap_Img' + i;

            // running console.log here gives expected values for both

            $(imgArea[i]).hover(   //imgArea[i] (selector) works correctly here

                function() {
                    $('#imgSwap').attr('src',imageSource[i]);  // imageSource[i] is undefined here
                },
                function() {
                    $('#imgSwap').attr('src','images/img0.png');
                });

        })(); // end anonymous function and execute

    }; // for loop

}); 

Tried the idea of using an anonymous function for scoping from another jQuery post. Seems to work OK but throws an undefined for the array value in the first hover function, I guess because it’s an inside function (hardcoded image sources work correctly there).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T16:58:31+00:00Added an answer on May 11, 2026 at 4:58 pm

    There is indeed a problem with your closures, and it has to do with your usage of the var i. Since your anonymous function has no local version of i, it’s using the version of the function above it. However, when it tries to access i at a later date, i == 11 (since that’s what made the loop terminate). To fix this, you need to declare a local version of i in each anonymous function, like this:

    for (var i=1; i<11; i++) {
    
        (function( ){  //anonymous function for scope                
                var index = i; // The important part!
    
                // It's not technically necessary to use 'index' here, but for good measure...
                imageSource[index] = 'images/img' + index + '.png';
                imgArea[index] = '#areamap_Img' + index;
    
                $(imgArea[index]).hover(
    
                        function() {
                                $('#imgSwap').attr('src',imageSource[index]);  // Here's where `index` is necesssary.
                        },
                        function() {
                                $('#imgSwap').attr('src','images/img0.png');
                        });
    
        })(); // end anonymous function and execute
    
    }; // for loop
    

    Additionally, there’s a small problem in your code you should fix just for good measure. You’re not accessing your local variables correctly; you should use:

    var imageSource = []; 
    var imageSource[0] = 'images/img0.png'  //load 0 position with "empty" png
    var imgArea = []
    

    Without the “var”, you’re declaring and accessing global variables. (If this is your intended behavior then I apologize.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 201k
  • Answers 201k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer It is probably cleaner and less error prone to use… May 12, 2026 at 8:15 pm
  • Editorial Team
    Editorial Team added an answer With <authentication mode="Windows"/> in your application and Anonymous access enabled… May 12, 2026 at 8:15 pm
  • Editorial Team
    Editorial Team added an answer The only way I know how to do this (without… May 12, 2026 at 8:15 pm

Related Questions

Lately, I'v been struggling with an annoying situation on ASP.NET MVC. Here's the story
How can I achieve the following structure without using tables or JavaScript? The white
I am attempting to persist what the users enters into a textbox without them
I have run in to a bit of a problem and I have done

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.