PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 16, 2022

[FIXED] Why does onclick's handling function not work as expected?

 October 16, 2022     dom, dom-events, javascript     No comments   

Issue

I have the following little piece of code:

var instance = this;
window.onload = function () {
    for (var i = 0; i < array.length; ++i) {
        var currentDivId= array[i];
        var currentDiv = document.getElementById(currentDivId);
        
        try {
            if (!currentDiv) {
                throw 'Div id not found: ' + currentDivId;
            }
            var image = document.createElement('img');
            image.src = 'img.jpg';
            image.onclick = function() {
                instance.doSomething(currentDivId);
            };
            
            currentDiv.appendChild(image);
        }
        catch(e) {
            console.warn('oops');
        }
    }
};

This code is passed an array of id of divs. What it does is that, it renders an image at each of those divs and set their onclick property.

Say I have an array of strings: ['abc', 'xyz']

I want the code to place an image inside <div id="abc"></div> and another image inside <div id="xyz"></div>.

When you click the first image, instance.doSomething function should be called with parameter 'abc' and vice versa.

But the code does not work as expected. It always calls instance.doSomething with the last parameter in the array, in this case, 'xyz'.

I'm new to JS and still don't have a solid grasp of its inner workings. What's wrong here and how can I fix it?

Any help appreciated.


Solution

image.onclick = function() {
    instance.doSomething(this.parentNode.id);
};

That should do it. Since we know that the image is inside the div we want to get at, just go one dom element up and get its id.



Answered By - Munter
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing