Arad Ahmadpour
Arad Ahmadpour

Reputation: 1

How to link a div with an id to an anchor link with js

I have a <div> with the ID “work1acc.” My goal is to link it to an anchor (#work1)—a section on my website. I’ve attempted to use code, but unfortunately, it’s not functioning as an anchor link. Here’s the code snippet I’ve tried:

JavaScript

document.getElementById('work1acc').addEventListener('click', function() {
    location.href = '#work1';`
});

AI-generated code. Review and use carefully. More info on FAQ. If anyone can provide assistance, I would greatly appreciate it! 🙏

Upvotes: 0

Views: 49

Answers (1)

tacoshy
tacoshy

Reputation: 13012

My goal is to link it to an anchor (#work1)—a section on my website.

The real issue is that you misuse terms here. An AI will have trouble figuring out when you misphrase or misuse keywords. An anchor is not an ID that you refer to. An anchor simply is a link that you can click on and will direct you to any resource (internal or external).

What you actually want to do is to use an anchor (<a>) and assign to the href attribute the value of the section ID you want to refer to, starting with the hash (for id).

/* for visualization purpose only */
section {
  min-height: 80vh;
  border: 2px dashed red;
  padding: 0.5rem;
  margin-bottom: 0.5rem;
}
<a href="#section-4">click me to go to Section 4</a>

<section id="section-1">Section 1</section>
<section id="section-2">Section 2</section>
<section id="section-3">Section 3</section>
<section id="section-4">Section 4</section>
<section id="section-5">Section 5</section>

Upvotes: 2

Related Questions