Vinicius Bazanella
Vinicius Bazanella

Reputation: 505

How do i make onClick and href work together?

I have an a element which has his own href and it works perfectly. The problem is that besides an href element i want to make an onClick function, but when i do so, the href is ignored:

<li><a href="#someSectionOfThePage" onClick={someFunction}>GO TO SECTION</a></li>

Using this syntax, the someFunction runs, but i'm not being redirected to #someSectionOfThePage.

Upvotes: 0

Views: 1928

Answers (4)

Harshit Agarwal
Harshit Agarwal

Reputation: 2420

Although it is not advisable but if you still want to use both then this might do the trick:

someFunction= ()=>{
  window.location.href("#someSectionOfThePage");
  //do your onClick stuff here
};

<li>
  <span onClick={this.someFunction}>GO TO SECTION</span>
</li>

Hope this helps!!

Upvotes: 0

yaswanth
yaswanth

Reputation: 159

You can also try to add a click event handler for li and make sure li and anchor tag a takes the same width.

Upvotes: 0

Ajith
Ajith

Reputation: 9

The href present in the a tag is not going to work because of the onClick event. After clicking the element, instead of redirecting you to the section of the page, it executes someFunction(). You may try adding location.href = "#someSectionOfThePage" to someFunction() which will do the work of href.

Upvotes: 0

Mosia Thabo
Mosia Thabo

Reputation: 4277

This should do the trick:

<li onClick={someFunction}>
   <a href="#someSectionOfThePage">GO TO SECTION</a>
</li>

When you click the <li> it will execute the function... and when you click the <a> it will process the href. Since you'll be clicking this element, both will work the same time.

Upvotes: 2

Related Questions