Web Development

Built by maltpress

[Solved]: Cannot read property ‘selectionStart’ of undefined – wpLink issues with 4.2

So…. that was a difficult couple of hours!

My Javascript has never been my strongest suit (I really should do something about that) so when the trusty bit of code I had to use the WordPress native “add link” dialogue started bumming out on me – on a lot of sites I’d recently built – it sent me into a bit of a flat spin.

This bit of code had been working fine for a long time, but improvements to TinyMCE in 4.2 suddenly stopped things from working with the error you can see in this post title.

Lots of huffing and puffing and comparing code later, and I discovered that the new version is looking for “this”… and if you don’t pass an editor (or text input) ID into the; function, it can’t find it. Which gives us this bit of code to replace what’s linked above:

$('.link-btn').live('click', function(event) {
        wpActiveEditor = true; //we need to override this var as the link dialogue is expecting an actual wp_editor instance $(this).attr('id') ); //open the link popup
        wpLink.newattr = $(this).attr('id');
        return false;

You’ll see some other additions I’ve made: wpLink.newattr (I know, it needs a better variable name) takes an ID, which I then use to make sure I pass the other attributes to the right input field when I close the dialogue box:

$('#wp-link-submit').live('click', function(event) {
        var linkAtts = wpLink.getAttrs();//the links attributes (href, target) are stored in an object, which can be access via  wpLink.getAttrs()
        var targetID = wpLink.newattr.replace('add_link_button_', '');
        $('#jou_nav_link_' + targetID).val(linkAtts.href);//get the href attribute and add to a textfield, or use as you see fit
        wpLink.textarea = $('.link-textfield');
        wpLink.close();//close the dialogue
        //trap any events
        event.preventDefault ? event.preventDefault() : event.returnValue = false;
        return false;

Now, all I have to do is roll this out across quite a lot of sites… and on a bank holiday, no less.

Back to blog

Leave a comment

By using this site you consent to our use of cookies. To find out more, see our privacy policy. Continue