0

How can i simulate with Javascript the click Event of a Bootstrap Button to perform the default actions that binded on the Button ?

I need this for automated Testing of a website.

Bootstrap add no Event on the Button himself, the events a bubbled to the body element and the work is done their.

$("btn.btn-outline-danger").click() is not working $("btn.btn-outline-danger").trigger("click") is not working

1
  • 1
    I believe $("btn.btn-outline-danger").click() should work if jQuery is loaded. It would help if you provided a bit of html code. Commented Jul 14, 2019 at 14:43

3 Answers 3

1

Try with this.

$(document).on('click', '.btn',function(){
    alert('click');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer - Your suggestion adds its own event handler, which I can trigger with .click () - unfortunately this does not trigger the already existing click events that run through the bootstrap framework.
0

Since Bootstrap uses jQuery as a dependency you can simulate a click event in jQuery way.

$('.btn').click(function(){
  console.log('Event Triggered');
});

Excluding jQuery, Vanillajs.

var button = document.getElementByClassName('.btn');
button.onclick = console.log('Event Triggered');

2 Comments

Your code binds code to the button. OP asks about triggering a click event with code, thus simulating a click. jQuery click() (without a function between the brackets) does this.
Thanks for the answer - Your suggestion adds its own event handler, which I can trigger with .click () - unfortunately this does not trigger the already existing click events that run through the bootstrap framework.
0

Events should bubble up to the parent (unless explicitly prevented). Consider this simple html structure:

<div class="parent">
    <div class="child"></div>
</div>

With the code below the parent has a function attached to the click event. When the child click event is triggered, the parent's event responds.

$(".parent").click(function() {alert("hello")}); // attach event
$(".child").click(); // trigger event

https://jsfiddle.net/epqdz2a1/

This should be the same in Bootstrap.

Vanilla js version:

document.querySelector(".parent").addEventListener("click", function(){alert("hello")});
document.querySelector(".child").click();

1 Comment

Event Bubbling does not work if a add my own click event to the Bootstrap Button :-(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.