Home > Software engineering >  click a element with data-video-id on page load with javascript?
click a element with data-video-id on page load with javascript?

Time:11-07

Hello I have a wordpress page that im trying to make it so that when someone hits my page with the #click_approved parameter on the url- it triggers a link with data-video attribute to open a modal. So far i drafted this JS but no luck

<script>
if(document.URL.indexOf("#click_approved") >= 0) { 
  document.querySelector('[data-video-id="5MS_V0SpRL8"]').click();
}
</script>

also tried this

<script> 
var element = document.querySelector("a[data-video-id='5MS_V0SpRL8']");
if(document.URL.indexOf('#click_approved') >= 0) { 
  setTimeout(function(){element.click();}, 5000); 
} 
</script> 

this is the page I'm trying to get the function to work on

https://www.homecarepulse.com/home-care-tv/recruitment-retention/#click_approved

any help is appreciated!

CodePudding user response:

You could just move querySelector into the setTimeout callback function.

<script> 
if(document.URL.indexOf('#click_approved') >= 0) { 
  setTimeout(function(){
      var element = document.querySelector("a[data-video-id='5MS_V0SpRL8']");
      element.click();
  }, 5000); 
} 
</script> 

or reduce wait time using a setInterval

<script>
(function() {
    if (document.URL.indexOf('#click_approved') === -1) return;
    let tm = setInterval(function(){
        var a = document.querySelector("a[data-video-id='5MS_V0SpRL8']");
        if (a) {
            clearInterval(tm);
            a.click();
        }
    }, 500);
})();
</script>

and here is another way using MutationObserver API, it's more efficient than the timer way. it ensures that click event can be triggered immediately once the element is rendered.

<script>
(function() {
    if (document.URL.indexOf('#click_approved') === -1) return;

    let observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (!mutation.addedNodes) return
        for (let node of mutation.addedNodes) {
            if (node.tagName == 'A' && node.getAttribute('data-video-id') == '5MS_V0SpRL8') {
                node.click();
                observer.disconnect();
            }
        }
      });
    });

    observer.observe(document.body, {
        childList: true
      , subtree: true
      , attributes: false
      , characterData: false
    });
})();
</script>
  • Related