Created
January 7, 2020 10:04
-
-
Save mx-rk-quyenl/cb7480a0b67466fb97f2c3271ae1b8bd to your computer and use it in GitHub Desktop.
Align center select option using javascript (Jquery)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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