I use a lot of "when user clicks on element then another element will be displayed as visible/hidden... aka toggle".
So I'm trying to make a general function to abide the DRY principal.
Before jumping into the code, I just wanted to state that there are still bugs. I just want to know before continuing if writing a function like the one below is necessary or if I should just ignore the DRY in this case and have lots of separate toggle functions. Or if it's necessary, would there be a more efficient method?
*Brief Description of Code
-There are 4 parameters
- The first two are mandatory, the last two are optional
- The index parameter is a string of numbers ex. "1.0","1"
- The reason I need the last two parameters is because I have elements that can't be easily targeted. For example, they don't have an #id. So to grab those generic elements, I use getElementsByTagName
Then I'll use the index parameter to get the element in the array.
index parameter: The number before '.' is the index of the clickElement and the number after '.' is the index of the toggleElement. clickElement = 1. toggleElement = 0.
function toggleClick(clickElement, toggleElement, condition, index) {
var toggleIndex;
var clickIndex;
if(condition === false){
if(index.indexOf('.') != -1){
//indexOf returns -1 if '.' is not found.
// Checks to see if two index is entered
indexArray = index.split('.');
clickIndex = indexArray[0];
toggleIndex = indexArray[1];
clickElement = document.getElementsByTagName(clickElement)[clickIndex];
toggleElement = document.getElementsByTagName(toggleElement)[toggleIndex];
}else{
//If there is no '.', that means only one index was entered.
// By function requirement, it should be the index of clickElement
clickElement = document.getElementsByTagName(clickElement)[index];
}
}
$(clickElement).click(function(){
$(toggleElement).toggle();
});
}
This is one of my first functions, and so I need some guidance on whether I'm writing bad code. Yes, this might be broad because there may be many different ways to write this function. But I just need to know if there's a more efficient way or if my way is okay.