Reputation: 330
I have following similar pieces of code:
document.getElementById('caption1').onclick = function () {
window.open("#abstract1","_self");
if(document.getElementById('abstract1').style.display == 'none') {
document.getElementById('abstract1').style.display = '';
}
else {
document.getElementById('abstract1').style.display = "none";
}
};
document.getElementById('caption2').onclick = function () {
window.open("#abstract2","_self");
if(document.getElementById('abstract2').style.display == 'none') {
document.getElementById('abstract2').style.display = '';
}
else {
document.getElementById('abstract2').style.display = "none";
}
};
document.getElementById('caption3').onclick = function () {
window.open("#abstract3","_self");
if(document.getElementById('abstract3').style.display == 'none') {
document.getElementById('abstract3').style.display = '';
}
else {
document.getElementById('abstract3').style.display = "none";
}
};
The code goes on so till 9. Instead of writing so many similar pieces of code how can I just write one which will work for. Perhaps I should write some Regex but how?
Upvotes: 0
Views: 936
Reputation: 13912
Just concatenate a variable with your string. Also taking @squints advice of using a function instead of creating a dozen anonymous function objects
someFunction(){
var id = "abstract" + this.id.substr(7);
window.open("#" + id,"_self");
el = document.getElementById(id);
el.style.display = (el.style.display === 'none') ? '' : "none";
}
for( var x = 0; x < 10; x++ ){
document.getElementById('caption' + x).onclick = someFunction;
}
Upvotes: 4