Skip to content

Instantly share code, notes, and snippets.

@mx-rk-quyenl
Created January 7, 2020 10:04
Show Gist options
  • Save mx-rk-quyenl/cb7480a0b67466fb97f2c3271ae1b8bd to your computer and use it in GitHub Desktop.
Save mx-rk-quyenl/cb7480a0b67466fb97f2c3271ae1b8bd to your computer and use it in GitHub Desktop.
Align center select option using javascript (Jquery)
function getTextWidth(txt) {
let $elm = $('<span class="tempforSize">'+txt+'</span>').prependTo('body');
let elmWidth = $elm.width();
$elm.remove();
return elmWidth;
}
function centerSelect($elm) {
const optionWidth = getTextWidth($elm.children(':selected').html());
const emptySpace = $elm.width() - optionWidth;
$elm.css('text-indent', (emptySpace/2));
}
// init screen
const centerSelectDOM = $('.centerSelect');
centerSelectDOM.each(function(){
centerSelect($(this));
});
// on change event
centerSelectDOM.on('change', function(){
centerSelect($(this));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment