How to prevent the popover div for hiding on clicking inside it for twitter bootstrap “dismissible popover”(data-trigger=“focus”)?

前端 未结 4 1340
时光说笑
时光说笑 2021-02-20 07:01

I have a a dismissible popover(data-trigger=\"focus\") with a text box inside it. But as soon as I click inside the text box to type it dissappear because of the \"data-trigger=

4条回答
  •  孤城傲影
    2021-02-20 07:23

    Clicks on the popover are hiding that popover because they are stealing the browser's focus. As soon as the button loses focus, the popover will be hidden (because we've set data-trigger="focus").

    To address exact question you asked:

    prevent the popover div for hiding on clicking inside it for twitter bootstrap “dismissible popover”(data-trigger=“focus”)?

    The simplest way to fix this is to prevent clicks inside the popover from stealing focus by:

    • Adding an event listener to catch clicks inside the popover
    • Calling preventDefault() on the caught event

    This will stop the focus from being stolen, and so stop the popover from being closed.

    Note: We need to add the event listener on mousedown rather than click, because that is when the focus is set by the browser.

    A more in-depth explanation of why we use mousedown and preventDefault() can be found on this StackOverflow answer: Prevent firing focus event when clicking on div

    $(function() {
      $('[data-toggle="popover"]').popover()
    })
    
    $('body')
      .on('mousedown', '.popover', function(e) {
        console.log("clicked inside popover")
        e.preventDefault()
      });
    
    
    
      
      
      
      
        Dismissible popover
      
    
    

提交回复
热议问题