Get width of dom element within plugin js code


(Ngô Minh Tuấn) #1

In my custom plugin, I need to get the width of a post’s child element in javascript.
The plugin’s javascript looks something like this

import { withPluginApi } from 'discourse/lib/plugin-api';

function initializePlugin(api) {
    api.decorateCooked($elem => {
        var html = '<custom-html-here>';
        $elem.append(html);
        var width = $elem.find('.custom-class').first().width();
        console.log('First console log width:' + width);
        $(window).on('resize orientationchange', function() {
            width = $elem.find('.custom-class').first().width();
            console.log('Second console log width:' + width);
        });
    });
}

export default {
  name: 'custom-plugin',
  initialize() {
    withPluginApi('0.5', initializePlugin);
  }
};

The first console log doesn’t show the right width which can be observed through browser inspector but second console log does. My guess is the dom inside plugin hasn’t got attached to document yet so that’s why the width is not correct.

Is there any way (e.g event raised from ember or discourse js) which I can use to obtain the size of dom element within plugin code ?