partiz
partiz

Reputation: 1216

Run jquery function via special anchor link a tag

Normally we can call a jquery function using this method:

<a id="mylink" href="#mylink2">link</a>
$(document).ready(function(){
    $("#mylink").click(function(){
    // do something
    });
});

Now I want to know if it is possible to call a jquery function via anchor link?

For example if an user loads a webpage by a url like (www.example.com/#mylink), Jquery runs an special function.

Something like this:

$(document).ready(function(){
        if(click on a tag mylink2 anchor)
        // do something
        });
    });

Upvotes: 0

Views: 36

Answers (2)

DinoMyte
DinoMyte

Reputation: 8868

I guess in order to figure out which element was clicked during hashchange, you would need to intercept 2 events.

var id;
$(window).on('hashchange',function(){
        if(id == "mylink")
          alert("mylink was clicked");
});

$('a').on('click',function()
{
  id = this.id; // sets the id of the anchor linked clicked for comparison.
});

Example : https://jsfiddle.net/DinoMyte/mb10r8ox/1/

Upvotes: 1

guest271314
guest271314

Reputation: 1

Try using hashchange event

$(window).on("hashchange", function() {
  alert("hashchange event")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<a id="mylink" href="#mylink2">link</a>
<div id="myLink2">myLink2</div>

Upvotes: 1

Related Questions