Unable to trigger any javascript events inside popover in bootstrap

Well, I dealt with this problem for several days, and I only found out that I can not fire any events inside the boot popover. I even tried calling alert() and it does nothing.

I have a popover with a button in it. When you press a button, the text on it changes. Any help? Here is the script . Thanks.

+4
source share
2 answers

As Michael noted in his answer, the popover element does not exist in HTML until a link is clicked. Therefore, the click handler cannot attach to it until the link is clicked. Thus, you can either move the click handler to the popover call, or use the jQuery on delegate, for example:

 $('.location').on('click','.text-btn',function () { alert('What\ going on!'); //$('.text-btn').toggle(); }); 

See this work in fiddle

This is done as follows: it attaches a click handler to an element with the location class. When something inside this element receives a click (for example, the text-btn ), the event bubbles up and fires this handler. However, the on handler only listens for events that are fired by certain elements (in this case, elements that have the text-btn ). Since the handler is bound to the .location element, and this element is not dynamic, it will always be available.

+7
source

The problem is that you are assigning event listeners to a node that does not yet exist. If you look at the HTML that is generated when you click on the Fire popover , the following HTML is generated:

 <div class="popover-content"> <button class="btn text-btn">Toggle me!</button> <button class="btn text-btn toggle-text">Un-Tobble me</button> </div> 

The problem is that this was created after your listener code is run in the document, so there is no listener on your button.

Hopefully someone else can tell you how to add a listener, as I cannot figure it out.

+2
source

Source: https://habr.com/ru/post/1491509/


All Articles