I recently discovered a method to link individual elements in an array with event handlers using a for loop in jQuery.
This informative tutorial guided me in the right direction:
Now, I have delved deeper and am attempting to connect multiple elements with the same prefix in an array to event handlers in jQuery.
The following code is functional:
var menu = new Array("#power", "#services", "#cashback", "#schedule");
$(document).ready(function(){
$(function() {
for(var i in menu)
{
(function() {
var x = menu[i];
var y = menu[i]+'_menu';
$(x).hover(
function () {
$(x).css({ backgroundColor: "#000", color: "#3ABCEF"});
$(y).show();
},
function () {
$(x).css({ backgroundColor: "#333", color: "#FFF"});
$(y).hide();
}
);
$(y).hover(
function () {
$(x).css({ backgroundColor: "#000", color: "#3ABCEF"});
$(y).show();
},
function () {
$(x).css({ backgroundColor: "#333", color: "#FFF"});
$(y).hide();
}
);
})();
}
});
});
What I really want to achieve:
var menu = new Array("#power", "#services", "#cashback", "#schedule");
$(document).ready(function(){
$(function() {
for(var i in menu)
{
(function() {
var x = menu[i];
var y = menu[i]+'_menu';
$(x,y).hover(
function () {
$(x).css({ backgroundColor: "#000", color: "#3ABCEF"});
$(y).show();
},
function () {
$(x).css({ backgroundColor: "#333", color: "#FFF"});
$(y).hide();
}
);
})();
}
});
});
UPDATE ::: Final implementation that works perfectly:
var menu = new Array("#power", "#services", "#cashback", "#schedule");
$(document).ready(function(){
for(var i in menu)
{
(function(x, y) {
$(x+','+y).hover(
function () {
$(x).css({ backgroundColor: "#000", color: "#3ABCEF"});
$(y).show();
},
function () {
$(x).css({ backgroundColor: "#333", color: "#FFF"});
$(y).hide();
}
);
})(menu[i], (menu[i] + '_menu'));
}
});