Search code examples
jquerycsstwitter-bootstraptooltip

Add Bootstrap Tooltip when Bootstrap Switch is Disabled


Similar to this question using a Bootstrap Button I am looking to add a tooltip to appear when my Bootstrap Switch is disabled.

I have this JSFiddle that disables the Switch when the map reaches a certain zoom as per the code below. I now want to add a tooltip that tells the user to zoom in when the Switch is disabled.

map.on('zoomend', function (e) {
    // Add/remove layers based on zoom level
    if (map.getZoom()>=5) {
        $("[name='my-checkbox2']").bootstrapSwitch('disabled',false);
    }
    else if (map.getZoom()<5) {
        $("[name='my-checkbox2']").bootstrapSwitch('disabled',true);
    }
});

Solution

  • It is to no use to assign a tooltip to the checkbox itself, since it is hidden - instead show / hide a tooltip for the outer .bootstrap-switch element which the checkbox is wrapped into :

    map.on('zoomend', function(e) {
        // Add/remove layers based on zoom level
        if (map.getZoom() >= 5) {
            $("[name='my-checkbox2']").bootstrapSwitch('disabled', false);
    
            $("[name='my-checkbox2']")
                .closest('.bootstrap-switch')
                .tooltip('destroy');
    
        } else if (map.getZoom() < 5) {
            $("[name='my-checkbox2']").bootstrapSwitch('disabled', true)
    
            $("[name='my-checkbox2']")
                .closest('.bootstrap-switch')
                .attr('title', 'Zoom more in')
                .tooltip();
    
        }
    });
    

    trigger zoomend immediately to update the tooltip status :

    map.fireEvent('zoomend')
    

    updated fiddle -> https://jsfiddle.net/ujzaakv3/3