Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to shorten the functions? I

https://prnt.sc/21vc411
As you can see on the link when i click one letter in left side or in right side, that letter should disappear and should go to the opposite side. For example, when i click "A" letter on the left it goes to right. I created one letter on each side, and as default the right one’s display is ‘none’. So when i click the one on the left the following function starts;

function myFunction() {
document.getElementById("aLetterLeftSide").style.display="none";
document.getElementById("aLetterRigtSide").style.display="inline-block";
}       

It works but i have to do it for every letter with different id’s. So there is approximately 50 functions 🙁 Is there a way to shorten it to less functions ? Thank you for your answers 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are binding your functions to your elements using Element ids (MDN Webdocs Link). When you have a bunch of elements that need the same function, just bind them use Element ClassName (MDN Webdocs Link) instead.

In the following example, I simple have letters with class defined as letter-span, and then I set the onclick (MDN Webdocs Link) property iteratively…

var letterspans = document.getElementsByClassName("letter-span");

var onclickfunc = function(e) {
  if(this.style.float) {
    this.style.float = '';
  } else {
    this.style.float = 'right';
  }
};

for(i = 0; i < letterspans.length; i++) {
  letterspans[i].onclick = onclickfunc;
}
<span data-letter="a" class="letter-span">A</span> | 
<span data-letter="b" class="letter-span">B</span> | 
<span data-letter="c" class="letter-span">C</span> | 
<span data-letter="d" class="letter-span">D</span> 

Note

The above is a full, working, stand-alone demo (please note: Minimal Reproducible Code). In this case, I did if(this.style.float){ and this.style.float = ''; you may need a different condition and setter, perhaps, if(this.classList.contains('rightside')) {.., and this.classList.add('rightside') along with this.classList.remove('rightside'). I didn’t do it this way, because, I wanted something fully reprocudible in a demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading