detect which word has been clicked inside link

Viewed 108

I'm working on a chrome extension that extracts every word clicked. This code works great for any word outside of a link:

$(document).click(function(e) {
  var t = '';
  var s = window.getSelection();
  if (s.isCollapsed) {
    s.modify('move', 'forward', 'character');
    s.modify('move', 'backward', 'word');
    s.modify('extend', 'forward', 'word');
    t = s.toString();
    s.modify('move', 'forward', 'character');
  } else {
    t = s.toString();
  }
  console.log(t);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">foo bar</a><br>
words not in link

However I also need to get the words clicked inside a link. so for example with this html:

<a href="#">foo bar</a>

I need to get "foo" when the word foo is clicked. Is there a way do to that with jQuery?

1 Answers

I found a way to see which character is clicked within a link. This also takes you to the webpage you have set for it to go to

var link = prompt('what would you like as a link');
var href = prompt("where would you like the link to go")
var splitLink = link.split('');
for(var i = 0;i<splitLink.length;i++){
  $('body').append('<a target="_blank">'+splitLink[i]+"</a>");
}
$('a').click(function(){
  alert('you clicked the '+$(this).html());
  window.open(href)
})

and if you wish you can also do this for multiple words if you wish to see which word is clicked

var link = prompt('what would you like as a link');
var href = prompt("where would you like the link to go")
var splitLink = link.split(' ');
for(var i = 0;i<splitLink.length;i++){
  $('body').append('<a target="_blank">'+splitLink[i]+" </a>");
}
$('a').click(function(){
  alert('you clicked the '+$(this).html());
  window.open(href)
})
Related