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.


您可以尝试MutationObserver ,它将侦听元素的css中的更改,然后在发生更改时运行单击事件。

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>

你可以试试这个....

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

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

链接地址: http://www.djcxy.com/p/83392.html

上一篇: 在视口中移除div中的类

下一篇: 如何在按钮变为可见时触发javascript事件?