Trying to group 3 functions

I am trying to group or merge these three functions.

var link1 = document.getElementById("w1");
if(link1){
document.getElementById("w1").onclick = function(){document.location = "a-given-web-section";};
}
var link2 = document.getElementById("w2");
if(link2){
document.getElementById("w2").onclick = function(){document.location = "another-section";};
}	
var link3 = document.getElementById("w3");
if(link3){
document.getElementById("w3").onclick = function(){document.location = "a-third-section";};
}

The problem is that each of them point at a different url in a website.

That’s why link elements usually contain the location in their href attribute.

And why you can wrap <a></a> tags around other elements in the page. Using Javascript for this is overkill.

Please forget about the html. There are design reasons to use javascript. It is a complex design with elements inside windows with paragraphs and backgrounds. The links are there but I need to implement them also by javascript. The functions works perfectly but I think that there must be a way to group them.

By the way, they are not just three of them but twelve.

Is it possible or should I leave them like that in the file?

Then your design has failed, because you’ve destroyed the meaning of an anchor tag with your design.

Can you ‘group’ the links? yes. Is it more complex than what you have now? yes.

1 Like

Hi @andresb, well generally speaking a good way to abstract away repetitive, hard-coded event handlers is using data attributes; for instance:

<p data-location="a-given-web-section">A given section</p>
<p data-location="another-section">Another section</p>
const handleClick = event => {
  window.location = event.target.dataset.location
}

document
  .querySelectorAll('[data-location]')
  .forEach(element => element.addEventListener('click', handleClick))

But as already noted there’s certainly a better solution for this particular scenario.

1 Like