KoolKabin
KoolKabin

Reputation: 17683

how can i extract text after hash # in the href part from a tag?

I have following a tags:

<a href="#tab1">Any tab1 Label</a>
<a href="#tab2">tab2 Label</a>
<a href="#tab3">Any tab3 Label</a>
<script>
function tellMyName()
{
    alert(this.href);
}

</script>

Now i want to bind the tellMyName function to all the a tags and get tab1 if Any tab1 Label is clicked, tab2 if tab2 Label is clicked and so on...

Upvotes: 23

Views: 45848

Answers (8)

Beena Shetty
Beena Shetty

Reputation: 3736

function tellMyName() {
    var str = this.prop("hash").substr(1)
    alert(str);
}

this.prop("hash") will return the hash value i.e #tab1

Upvotes: 1

Antonio Kobashikawa
Antonio Kobashikawa

Reputation: 91

You can use something like this:

...
var activeTab = $(this).attr("href");
$(activeTab).fadeIn();
...

This use href="#tab-id" for locate #tab-id element you want, and fade in.

Upvotes: 0

sje397
sje397

Reputation: 41862

function tellMyName() {
  alert(this.hash.substr(1));
}

$('a').click(tellMyName);

Upvotes: 44

alex
alex

Reputation: 490497

You can do something like this

var fragment = $('a#my-link')[0].hash.substr(1);

Check it out.

Upvotes: 6

Reigel Gallarde
Reigel Gallarde

Reputation: 65274

function tellMyName() {
  alert(this.hash.replace('#',''));
}

$('a').click(tellMyName);

crazy fiddle

Upvotes: 2

Alpesh
Alpesh

Reputation: 5405

Try this -

<a href="#tab1">Any tab1 Label</a>
<a href="#tab2">tab2 Label</a>
<a href="#tab3">Any tab3 Label</a>

<script type="text/javascript">
$('a').click(function(){
alert(this.hash.split('#')[1]); //This will alert # part in clicked anchor tag
});
</script>

Upvotes: 0

rob waminal
rob waminal

Reputation: 18419

function tellMyName() {
    var str = this.href.split("#")[1];
    alert(str);
}

Not all the time only the hash part will be displayed on the link. Sometimes the Host is added to the href. By splitting the href with the hash (#) and get the second part of the split string, you'll get what you want.

Upvotes: 25

Chinmayee G
Chinmayee G

Reputation: 8117

<script>
function tellMyName()
{
    var text = this.href;
    text = text.replace("#","");
    alert(text);
}

</script>

Upvotes: 0

Related Questions