hellzone
hellzone

Reputation: 5246

How to trigger a javascript event when a button becomes visible?

I am using some third party js and html library(I don't want to update this library). There is an "apply all" button in HTML and what I want to do is "click this button when it becomes visible."

<div class="confirm" ng-show="newFilters.length">
    ....
    <button class="btn btn-primary">Apply All</button>
</div>

EDIT: When the button becomes visible click function should trigger.

Upvotes: 1

Views: 5904

Answers (5)

webdevanuj
webdevanuj

Reputation: 675

try this:

setInterval(function(){
  if($("button.btn").is(':visible')){
    $(this).trigger('click');
    alert('button click');
  }
},1000);


it check every 1 second that button is visible or not and if visible trigger button click

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can try MutationObserver that will listen for changes in css of element and then you can run click event when change happens.

setTimeout(function() {
  $('button').css('display', 'block');
}, 2000);

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if ($('button').css('display') !== 'none') {
      $('button').click();
    }
  });
});

observer.observe(document.querySelector('button'), {
  attributes: true,
  attributeFilter: ['style']
});

$('button').click(function() {
  alert('clicked');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-primary" style="display: none;">Apply All</button>

Upvotes: 3

Rahul Arora
Rahul Arora

Reputation: 4533

You can simply do:

<div class="confirm" ng-show="newFilters.length">
    ....
    <button ng-click="newFilters.length && myFunction()" class="btn btn-primary">Apply All</button>
</div>

In controller:

$scope.myFunction(){
    console.log("hello");
}

Upvotes: 0

Arun AK
Arun AK

Reputation: 4370

As epascarello, we can use a timer to check whether the button is visible or not. So, you can use setInterval in your code.

setInterval(function(){
  if($("#show").is(':visible')){
    console.log("run the code");
  }
},2000);

Here is the jsFiddle link

Upvotes: 0

Amar Srivastava
Amar Srivastava

Reputation: 373

you can try this....

if($('#Element_name').is(':visible'))
{
    // you code goes here
}

Upvotes: 0

Related Questions