I have two similar pieces of code in two different functions of my project and I want to get rid of the repeating code. How can I do that?
getArray("my-hand").forEach(function(elem){
$(elem).mouseover(function(){
$(this).css({'top': '1em'});
});
$(elem).mouseout(function(){
$(this).css({'top': '0em'});
});
$(elem).click(function(){
var cardNode = $(this).get(0);
//some jquery animation
play(cardNode,time);
});
})
and the second piece
getArray("my-hand").forEach(function(elem){
$(elem).mouseover(function(){
$(this).css({'top': '1em'});
});
$(elem).mouseout(function(){
$(this).css({'top': '0em'});
});
$(elem).click(function(){
var cardNode = $(this).get(0);
//a function with another jquery animation
validateCardAndAddForCollection(checkNumber,cardNode,time);
});
})
One way is to put it in a function, and pass as an argument to that function a callback that will execute the desired code:
function handleCards (cb) {
getArray("my-hand").forEach(function(elem){
$(elem).mouseover(function(){
$(this).css({'top': '1em'});
});
$(elem).mouseout(function(){
$(this).css({'top': '0em'});
});
$(elem).click(function(){
var cardNode = $(this).get(0);
//some jquery animation
cb(cardNode);
});
});
}
handleCards(function (cardNode) {
play(cardNode, time);
});
handleCards(function (cardNode) {
validateCardAndAddForCollection(checkNumber,cardNode,time);
});