HTML Selection in different scenarios

47 views
Skip to first unread message

Nazar Hussain

unread,
Feb 28, 2014, 4:10:31 PM2/28/14
to ra...@googlegroups.com
Hi, 

I have to implement a logic in my application in which Rany could be beneficial for me. Here is the scenario. I have a contentEditable div with a lot of html element (content) in it. Now I want to get html of selection in these scenarios: 

  • If I place cursor in one line and don't select any thing
    • I want html of the complete line in which my cursor is
    • I want html of all lines before current line
    • I want html of all lines after current line
  • If I select any thing 
    • I want to get selected html (which is straight forward) 
    • I want to get all html before my selection
    • I want to get all html after my selection

Please guide me how can I use Rangy in my scenario. 

Would much appreciate your help.

Nazar Hussain

unread,
Mar 4, 2014, 9:19:31 AM3/4/14
to ra...@googlegroups.com
I found the trick to use it: 


jQuery.fn.getSelectionRange = (el)->
element = if el? then $(el)[0] else document.activeElement
selection = rangy.getNativeSelection()
# If a range is selected
if selection.type == 'Range'
rangy_selection = rangy.saveSelection()
reg = /<span .*?class="(.*?rangySelectionBoundary.*?)">(.*?)<\/span>/gi
start = reg.exec(element.innerHTML)
end = reg.exec(element.innerHTML)
rangy.removeMarkers(rangy_selection)
return { start: start.index, end: end.index - start[0].length}
else if selection.type == 'Caret'
# If caret is inside a li tag
if $(selection.baseNode).parents("li").length > 0 
li_el = $(selection.baseNode).parents("li")[0]
$(li_el).wrap($("<span />").addClass("rangySelectionBoundary"))
length = $(li_el).parents("span.rangySelectionBoundary:first")[0].innerHTML.length
reg = /<span .*?class="(.*?rangySelectionBoundary.*?)">(.*?)<\/span>/gi
start = reg.exec(element.innerHTML)
$(li_el).parents('span.rangySelectionBoundary').contents().unwrap()
return { start: start.index, end: start.index + length}
else 
document.execCommand 'formatBlock', null, '<h1>'
h1 = $(element).find('h1')[0]
length = h1.innerHTML.length
reg = /<h1>.*<\/h1>/gi
start = reg.exec(element.innerHTML)
$("<br>").insertAfter(h1)
$(h1).contents().unwrap()
return { start: start.index, end: start.index + length}

This solved my problem. 
Reply all
Reply to author
Forward
0 new messages