How to remove/hide bootstrap tooltip when element is removed from the DOM

拈花ヽ惹草 提交于 2019-12-24 17:22:16

问题


I'm currently working on a project in ReactJS. Some of my components are not rendered all the time but change dynamically based on certain conditions. When these components have a tool tip attached to them, I'm noticing that if the tooltip was active when the element was hidden, the tooltip does not go away. I'm looking for a way to remove or at least hide this tooltip when the element is not being rendered.

This is how I'm activating the tooltips using jQuery:

$(document).ready(function() {
      $("body").tooltip({ selector: '[data-toggle=tooltip]', placement: 'bottom' })
    })

This is how I'm using it within the html (or jsx):

<a className="icon-btn" onClick={ () => {
//on Click I remove this parent element and show something else
}}>
<i className="fa fa-lg fa-pencil-square" title="Edit" data-toggle="tooltip"></i>
</a>

Note I have not been able to select all elements by tooltip using:

$('[data-toggle=tooltip]').tooltip()

Apparently that is because I am adding elements dynamically? At least that is what my research so far shows


回答1:


$('.tooltip').tooltip('hide');




回答2:


I was having a similar problem and I know that the question is already a bit old but I post my solution, maybe it helps someone in the future... (It's an Angular-TypeScript-JQuery mixture but the principle is the same.)

In the component:

/* Toggles the Bootstrap 4 tooltip of an HTML element. */
private tooltip(elem: HTMLElement, action: string): void {
    (<any>$(elem)).tooltip("dispose");
    (<any>$(elem)).tooltip({ container: "body" });
    (<any>$(elem)).tooltip(action);
    (<any>$(elem)).tooltip("update");
}

In the view:

<someElement data-toggle="tooltip" title="..."
  (mouseenter)="tooltip($event.target,'show')"
  (mouseleave)="tooltip($event.target,'hide')">
</someElement>

So basically instead of using a global $('[data-toggle=tooltip]').tooltip() for activating all tooltips at once – which wouldn't work anyway if you have tooltips not being part of the DOM at the time this code is called because the page is generated dynamically by some JS framework for example – you only attach the tooltips to the elements when the cursor enters them, and destroy them immediately when it leaves.

(The { container: "body" } and "update" options are only to prevent positioning issues like this for more complex layouts.)



来源:https://stackoverflow.com/questions/39421249/how-to-remove-hide-bootstrap-tooltip-when-element-is-removed-from-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!