Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a click on a href value using jQuery

Tags:

jquery

I have the following HTML code in the backend, ie.

<div class="navi">
  <a class="" href="0"></a>
  <a class="" href="1"></a>
  <a class="" href="2"></a>
  <a class="" href="3"></a>
</div>

Apologies for the basic question but I would like to use jQuery to capture the user's click when they only click on the href value of "0"

Basically want to hide a div called "info" when the user clicks on the where the href="0"

Unsure how to do?

Thanks.

like image 295
tonyf Avatar asked Jun 02 '10 02:06

tonyf


1 Answers

You can use the attribute-equals selector, like this (though I don't think that's a valid href):

$("a[href=0]").click(function() {
  $("#info").hide();
});

A better approach, if possible, would be to give the <a> a better href that points to the <div>, like this:

<div class="navi">
  <a class="" href="#info"></a>
  <a class="" href="#info1"></a>
  <a class="" href="#info2"></a>
  <a class="" href="#info3"></a>
</div>

Then you can use a more generic click handler, relating to the corresponding <div> like this:

$(".navi a").click(function() {
  $(this.hash).toggle();
});

This would toggle <div id="info"> when you clicked the href="#info" link, the same or the others...if your links all relate to divs, this is a much better way to go, and it degrades gracefully with javascript disabled.

like image 114
Nick Craver Avatar answered Nov 05 '22 01:11

Nick Craver