Using Jquery, which <a> tag was clicked
Question
I am trying to use jQuery to find the Text of the link that was clicked. Below is the code snippet.
<li><a id="PAYROLL" href="../PayrollAdmin/Payroll_Default.aspx"><span>PAYROLL</span> </a> </li>
<li> <a id="WELFARE" href="../HRAdmin/Welfare_Default.aspx"><span>WELFARE</span></a> </li>
This is my jquery code
<script type="text/javascript">
$("a").click(function () {
var LinkText= $(this).text();
alert(LinkText);
});
</script>
NB: i donot want to use onclick event listener to track this. Help
EDIT Now here is the real thing i want achieve. I am trying to track my site using mixpanel, but each time i use this code, it dosen't track.
//Mixedpanel sdk loaded above already
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function (e) {
mixpanel.track_links(this.id, this.id +" was clicked", {
"referrer": document.referrer
});
});
});
</script>
Solution
First of all your code needs to be in a document ready handler or it may not run, depending on your scripts being at the top or the bottom of the page. Then you can do this -
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function (e) {
e.preventDefault()
alert(this.id); // because your id and text match
});
});
</script>
OTHER TIPS
use document ready
like this
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function (e) {
e.preventdefault()
var LinkText= $(this).text();
alert(LinkText);
});
});
</script>
I would do something like this:
$("a").click(function(event){ //bind an event listener to all links on the page
event.preventDefault(); //prevent the default action (a redirect) from occurring
console.log($(this).text()); //log the text from the clicked link
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow