javascript - Improving code for a jQuery Button -
i'm starting js ans jquery , i've been trying improve code bootstrap 3 button i'm working on.
it has 2 inside spans, 1 text , 1 chevrons font icons.
i wondering if there way optimize code (just sake of learning).
here working code.
first html
<button type="button" class="btn btn-default btn-lg btn-imgs"> <span class="btn-imgs-toggle">ocultar imágenes </span> <span class="glyphicon glyphicon-chevron-up"></span> </button>
now jquery:
$('.btn-imgs').click(function(){ $('.thumbnail img').toggle(); //variables var icono = $(this).children('.glyphicon'); var $text = $(this).children('.btn-imgs-toggle'); //cambia texto del boton $text.toggleclass('mostrar'); //si el texto y el icono coinciden con un tipo cambialos al otro if( $text.hasclass('mostrar') && $(icono).is('.glyphicon-chevron-up')){ $text.text('mostrar imágenes'); $(icono).removeclass('glyphicon-chevron-up').addclass('glyphicon-chevron-down'); } else { $text.text('ocultar imágenes'); $(icono).removeclass('glyphicon-chevron-down').addclass('glyphicon-chevron-up'); } });
thanks lot inputs on this. i've been learning quite lot searching through other posted questions.
personally, don't think there reason double check on state of children, unless have other scripts modify these elements. also, icono
jquery object when define it, there no reason wrap jquery method.
if writing this, approach way:
$(body).on('click', '.btn-imgs', function(e) { e.preventdefault(); $('.thumbnail img').toggle(); // how sure toggling correct state? // consider including in conditional, don't know purpose of // this, leave is. $(this).find('.glyphicon').toggleclass('glyphicon-chevron-down glyphicon-chevron-up') .siblings('.btn-imgs-toggle').toggleclass('mostrar').text(function () { return ($(this).hasclass('glyphicon-chevron-down') ? 'mostrar' : 'ocultar') + ' imágenes'; }); });
Comments
Post a Comment