# Dynamic button actions and for() loops

**URL:** <https://forum.kirupa.com/t/dynamic-button-actions-and-for-loops/53012>\
**Category:** flash\
**Created:** [May 29, 2004, 10:22pm UTC](https://forum.kirupa.com/t/dynamic-button-actions-and-for-loops/53012 "2004-05-29T22:22:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Big\_Al](https://avatars.discourse-cdn.com/v4/letter/b/dc4da7/32.png) [@Big\_Al](https://forum.kirupa.com/u/Big_Al)\
**Post date:** [May 29, 2004, 10:22pm UTC](https://forum.kirupa.com/t/dynamic-button-actions-and-for-loops/53012/1 "2004-05-29T22:22:19Z")

</div>

Hi, I’m having a problem with dynamically giving actions to buttons. This code, contained within another button, calls the function(s):

```auto
on (press) {
	initSection("faces");
}

```

The initSection() function is called, which in turn calls the setButtonActions() function 9 times. Each time, it attaches a movie clip from the library (faces1, faces2, etc.), giving it the same \_x and \_y as a corresponding box (9 boxes, with instance names dotbox1, dotbox2, etc. The boxes are permanently in a nice little grid, used as outlines).

Each time, it gives the button within each of the attached movie clips an onPress function (\_root[kind + j].button.onPress = …) to startDrag (\_root[kind + j]);. What I want to have happen is that it will start a drag of it’s movie clip on the main timeline.

However, what happens is that when I press on any button, it starts dragging the last dynamically attached movie clip. I think this is happening because it looks for \_root[kind + j], but using the most recent value of j (the previous, and final, time the setButtonActions() function was called, instead of the value of j when it’s actions were being set. Therefore, it uses j = 9 (since that was the value of j the last time setButtonActions() was called), and drags \_root.faces9. Does anyone know how to work around this? I’ve already tried replacing \_root[kind + j] with \_parent, but this seems to drag everything on the stage. The code is below, set in the actions of the frame.

```auto
stop ();
function initSection (section) {
	k = 2000;
	partName = new Array ();
	dotbox = new Array ();
	for (i = 1; i <= 9; i++) {
		_root.attachMovie (section + i, section + i, k);
		partName* = eval (section + i);
		dotbox* = eval ("dotbox" + i);
		_root.partName*._x = _root.dotbox*._x;
		_root.partName*._y = _root.dotbox*._y;
		setButtonActions (section, i);
		k++;
	}
	// end of for
}
// End of the function
function setButtonActions (kind, numOfClipToSet) {
	j = numOfClipToSet;
	_root[kind + j].button.onPress = function () {
		startDrag (_root[kind + j]);
	};
	_root[kind + j].button.onRelease = function () {
		stopDrag ();
	};
	_root[kind + j].button.onReleaseOutside = function () {
		stopDrag ();
	};
}

```

I also was hoping to keep setButtonActions() a seperate function, because I need to call it later on for other purposes.

Thanks! 🍺
