jquery - How to tell if caret is within H1 tag? -
i building wysiwyg content editable. want bold button highlight when caret within bold text, etc. have working, can't figure out how same h1 & h2. commandstate doesn't seem work items.
my js code:
setinterval(function () { var isbold = document.querycommandstate("bold"); var isitalic = document.querycommandstate("italic"); var isunderlined = document.querycommandstate("underline"); if (isbold) { $('button[rel=bold]').addclass('active'); } else { $('button[rel=bold]').removeclass('active'); } if (isitalic) { $('button[rel=italic]').addclass('active'); } else { $('button[rel=italic]').removeclass('active'); } if (isunderlined) { $('button[rel=underline]').addclass('active'); } else { $('button[rel=underline]').removeclass('active'); } }, 100);
simplified test case: http://jsfiddle.net/kthornbloom/gl4xs/
how can highlight h1 & h2 buttons when caret within them , there more compact way of writing this?
you going need range in order that. can either document.selection
or window.getselection
depending on browser using. wouldn't have continual interval running, rather listen keyup
, mouseup
on editable div
here sample code accomplish want. http://jsfiddle.net/bplumb/gl4xs/2/
$('#editor').on('keyup', function(){ rangemouseup(); }); $('#editor').on('mouseup', function(event){ $('button').removeclass('active'); $('button[rel='+event.target.nodename+']').addclass('active'); }); function rangemouseup(){ if (document.selection){ $(document.selection.createrange().parentelement()).trigger('mouseup'); } else if (window.getselection){ var range = window.getselection().getrangeat(0); $(range.commonancestorcontainer.parentnode).trigger('mouseup'); $(range.commonancestorcontainer).trigger('mouseup'); } }
edit
if need work parent nodes of caret cycle through dom , adjust styles needed. http://jsfiddle.net/bplumb/gl4xs/5/
$('#editor').on('mouseup', function(event){ $('button').removeclass('active'); var node = event.target; while(node.nodename != 'div'){ $('button[rel='+node.nodename+']').addclass('active'); node = node.parentnode; } });
Comments
Post a Comment