Javascript: click on element instead of button Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Javascript: click on element instead of button without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have simple code where is 4 containers with buttons. Now I tried to make whole element clickable to redirect to site specific to the container.

One element like I have in example working fine but when I add more than one, others will not work.

There is facebook, youtube, google, and twitter container and each of them have specific link to redirect.

So I need to make more than one element correctly clickable not only on a button but on whole element.

var el = document.getElementById("container");

if (el.addEventListener) {
  el.addEventListener("click", function() {
    document.getElementById("button").click();
  }, false);
} else {
  el.attachEvent("onclick", function() {
    document.getElementById("button").click();
  });
}
#container {
  background: coral;
  padding: 32px;
  margin: 16px;
  cursor: pointer;
}
<div id="container">

  <a id="button" href="https://google.sk/">Google</a>

</div>

<div id="container">

  <a id="button" href="https://youtube.com/">Youtube</a>

</div>

<div id="container">

  <a id="button" href="https://facebook.com/">Facebook</a>

</div>

<div id="container">

  <a id="button" href="https://twitter.com/">Twitter</a>

</div>

Answer

In HTML structure, id must be unique, you can use class instead, but you need also then to loop through these items (snippet included below)

var elements = document.querySelectorAll(".container");

elements.forEach(el => {
  if (el.addEventListener) {
    el.addEventListener("click", function() {
      el.querySelector(".button").click();
    }, false);
  } else {
    el.attachEvent("onclick", function() {
      el.querySelector(".button").click();
    });
  }
});
.container {
  background: coral;
  padding: 32px;
  margin: 16px;
  cursor: pointer;
}
<div class="container">

  <a class="button" href="https://google.sk/">Google</a>

</div>

<div class="container">

  <a class="button" href="https://youtube.com/">Youtube</a>

</div>

<div class="container">

  <a class="button" href="https://facebook.com/">Facebook</a>

</div>

<div class="container">

  <a class="button" href="https://twitter.com/">Twitter</a>

</div>

I’m just curious – why you want to handle click with JavaScipt? You can instead handle this with:

<a href="google.sk">
  <div class="container">google</div>
</a>

Have you tried that approach instead?

We are here to answer your question about Javascript: click on element instead of button - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji