Nikunj Madhogaria
Nikunj Madhogaria

Reputation: 2287

jQuery selector for target event?

I have the following CSS and HTML:

a {
  padding: 20px;
}
div {
  background: yellow;
  margin: 600px 0;
}
<a href="#target_id_1">link 1</a>
<a href="#target_id_2">link 2</a>
<a href="#target_id_3">link 3</a>
<a href="#target_id_4">link 4</a>
<a href="#target_id_5">link 5</a>
<div id="target_id_1" class="target_class">I'm the target 1!</div>
<div id="target_id_2" class="target_class">I'm the target 2!</div>
<div id="target_id_3" class="target_class">I'm the target 3!</div>
<div id="target_id_4" class="target_class">I'm the target 4!</div>
<div id="target_id_5" class="target_class">I'm the target 5!</div>

I want to perform certain jquery operations when divs with class "target_class" are targeted.

I know this can be achieved by adding a common class to these a tags (say, "link") and then binding a click event handler with that class like this:

$(".link").click(function(){
    //code
});

What I needed to know was: Is there a jQuery handler for target event for a particular class/id?

Something like:

$(".target_class").target(function(){
   //code
});

If not, are there any alternatives to achieve this?

Upvotes: 0

Views: 114

Answers (2)

Ian Hazzard
Ian Hazzard

Reputation: 7771

The way this works is the selector (a[href^="#target"]) matches every <a> tag whose href begins with #target.

$('a[href^="#target"').click(function(){ alert('You targeted something.'); });
a {
  padding: 20px;
}
div {
  background: yellow;
  margin: 600px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a href="#target_id_1">link 1</a>
<a href="#target_id_2">link 2</a>
<a href="#target_id_3">link 3</a>
<a href="#target_id_4">link 4</a>
<a href="#target_id_5">link 5</a>
<div id="target_id_1" class="target_class">I'm the target 1!</div>
<div id="target_id_2" class="target_class">I'm the target 2!</div>
<div id="target_id_3" class="target_class">I'm the target 3!</div>
<div id="target_id_4" class="target_class">I'm the target 4!</div>
<div id="target_id_5" class="target_class">I'm the target 5!</div>

Upvotes: 1

Freez
Freez

Reputation: 7568

I think this event does not exist in js, but you can handle hash change :

$(window).on('hashchange', function(){
   if ( $(this.location.hash).hasClass('target_class') ){
      // do stuff
   }
});

Upvotes: 1

Related Questions