Home > front end >  How to programmatically hover the item and click button in js
How to programmatically hover the item and click button in js

Time:09-23

Here is the demo link
Note: This demo is static in reality there will be dynamic list and button functionality.

On hover of item two buttons are showing.

Problem:
I want to programmatically hover each of the items and click on button using JS. This is a third party website UI demo and I want to handle it using my Chrome's console tab, if that's possible.

CSS:

.row .actions {
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    height: 44px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding: 8px 15px 8px 2px;
}

HTML:

<ul id="list">
   <li>item 1</li>
   <li>item 2</li>
   <li>item 3</li>
</ul>

JQuery:

$("#list li").hover(
    function() {
        $(this).append('<button id="but1" onclick="button1()">Button1</button>'  
            '<button id="but2" onclick="button2()">Button2</button>');
    },
    function() {
        $('#but1').remove();
        $('#but2').remove();
    });
    
    function button1(){ console.log("button1") }
    
     function button2(){ console.log("button2") }

CodePudding user response:

I think this is what you are looking for:

$("#list li").hover(
  function() {
    $(this).append('<button id="but1" onclick="button1()">Button1</button>'  
      '<button id="but2" onclick="button2()">Button2</button>');
  },
  function() {
    $('#but1').remove();
    $('#but2').remove();
  });

function button1(item) {
  console.log("button1")
}

function button2(item) {
  console.log("button2")
}

async function autoHoverAndClick() {
  for await (item of Array.from($("#list li"))) {
    await new Promise((res) => {
      item.dispatchEvent(new Event('mouseover'));
      $('#but1').click();
      $('#but2').click();
      console.log("------------------")
      setTimeout(() => {
        item.dispatchEvent(new Event('mouseout'));
        res()
      }, 1500)
    })
  }

}

(async() => await autoHoverAndClick())()
.row .actions {
  display: block;
  position: absolute;
  top: 0;
  right: 0;
  height: 44px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 8px 15px 8px 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>

  • Related