0

i have a function that i want to start with different handlers. but i can't get it right.

first i did have all the functions in separated lines.

$("#title_album").mouseup(function(){ menu_changer("_album") });
$("#title_animals").mouseup(function(){ menu_changer("_animals") });
$("#title_date").mouseup(function(){ menu_changer("_date") });
$("#title_nature").mouseup(function(){ menu_changer("_nature") });
$("#title_people").mouseup(function(){ menu_changer("_people") });
$("#title_place").mouseup(function(){ menu_changer("_place") });
$("#title_settings").mouseup(function(){ menu_changer("_settings") });
$("#title_stillife").mouseup(function(){ menu_changer("_stillife") });
$("#title_urban").mouseup(function(){ menu_changer("_urban") });

i tried to get it in a 'for' loop.

var menu_function_array = ["_album", "_animals", "_date", "_nature", "_people", "_place", "_settings", "_stillife", "_urban"];
for (var i = 0; i < menu_function_array.length; i = i + 1) {
    $(menu_function_array[i]).mouseup(function(){ menu_changer(menu_function_array[i]) });
}

now all my buttons do all the the work one the last button in the array.

how can i get this right? Thanks in advance

4 Answers4

1

Add more jQuery (or use a closure)

var menu_function_array = ["_album", "_animals", "_date", "_nature", "_people", "_place", "_settings", "_stillife", "_urban"];

$.each(menu_function_array, function(_, menu_function) {
    $('#title' + menu_function).mouseup(function(){ 
        menu_changer(menu_function) 
    });
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

If you use $.each for your loop you will create a closure for the indexing that doesn't exist using for

$.each(menu_function_array, function(i){
    var selector='#title'+menu_function_array[i];
    $(selector).mouseup(function(){ menu_changer(menu_function_array[i]) });
});

Also you were missing #title in selector

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

You have to remove the code that uses a index from the loop otherwise it will take the last value of i variable;

var menu_function_array = ["_album", "_animals", "_date", "_nature", "_people", "_place", "_settings", "_stillife", "_urban"];
for (var i = 0; i < menu_function_array.length; i = i + 1) {
   changeMenu(i);
}

function changeMenu(index) {
   $(menu_function_array[index]).mouseup(function(){ menu_changer(menu_function_array[index])    });
}
vpa2
  • 136
  • 4
0

You can consider using one selector with start with selector, than get the suffix by splitting the current id.

Code:

$("div[id^='title']").mouseup(function () {
    menu_changer("_"+$(this).attr('id').split("_")[1])
});

Demo: http://jsfiddle.net/IrvinDominin/wfvN9/

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111