3

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
youpielove
  • 41
  • 6
  • maybe you could implement some regex to replace all HTML after s.toString()? – Moebius Nov 01 '18 at 18:57
  • Very interesting question. I didn't know offhand how to accomplish this, but the JSFiddle in the answer to this post - https://stackoverflow.com/questions/43571090/detect-which-word-has-been-right-clicked-on-within-a-text/43571577 is promising. I tested it in Chrome (left-clicking) and it brought up each word correctly. Granted the example isn't inside an anchor tag, it could give you some insight – Rob Scott Nov 02 '18 at 00:27
  • 1
    unfortunately window.getSelection(); doesn't capture the selection when you click on a link tag like "a", unless the "a" tag doesn't have the "href" attribute. – Jose Rodriguez Nov 02 '18 at 04:40

1 Answers1

0

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)
})
Daniel
  • 23
  • 4