Jitender
Jitender

Reputation: 7971

How to prevent anchor href action from child element click

I want to prevent the page from reloading when the user clicks on the close button. The anchor should only work when the user clicks anywhere expect close button. I have used stopPropagation but it seems not working in this case. here is my fiddle

<a href="https://jsfiddle.net/9h1bw037/">
  <div>go to google</div>
  <button class="close">
    close
  </button>
</a>


$('.close').click(function(e) {
  e.stopPropagation()
  console.log('clicked')
})

Upvotes: 0

Views: 1488

Answers (1)

Bharatsing Parmar
Bharatsing Parmar

Reputation: 2455

You can try with return false Updated fiddle

$('.close').click(function(e) {
  e.stopPropagation()
  console.log('clicked')
  return false;
})

For react you can try this example fiddle

class Hello extends React.Component {
    handleClose = (e) => {
    e.stopPropagation();
    }

  handleAnchor = () => {
    window.location="https://jsfiddle.net"
  }

  render() {
    return <div>
    <a onClick={this.handleAnchor}>
      <div>Go to google</div>
      <button onClick={this.handleClose}>
        close
      </button>
    </a>
    </div>;
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

Upvotes: 3

Related Questions