ShubhamPlayZ
ShubhamPlayZ

Reputation: 25

How do i get an element to detect mouse hover

The HTML is too long. The full. is the only part that really matters

var buttons = document.getElementsByTagName('button');

for (i = 0; i < buttons.length; i++) {
  console.log(buttons[i])
  buttons[i].onmouseenter = function() {
    console.log('hello')
  }
}
<div id='buttons'>
  <a href='https://discord.com/api/oauth2/authorize?client_id=775316623220277248&permissions=391232&scope=bot' target='_blank'>
    <button id='invbutton'><i class="fab fa-discord fa-3x"></i>Invite</button>
  </a>
  <button>Support</button>
</div>

I have defined the script tag at the end of the HTML file. I have also tried adding event listeners which did not work. However, the 'hello' is console logged when the button is pressed for some reason

Upvotes: 1

Views: 2143

Answers (2)

Sarun UK
Sarun UK

Reputation: 6766

use onmouseover event.

<button onmouseover="handleHover()">Support</button>

var buttons = document.getElementsByTagName('button');

  function handleHover() {
   console.log('Hovered');
  }
<div id='buttons'>
  <a href='https://discord.com/api/oauth2/authorize?client_id=775316623220277248&permissions=391232&scope=bot' target='_blank'>
    <button id='invbutton'><i class="fab fa-discord fa-3x"></i>Invite</button>
  </a>
  <button onmouseover="handleHover()">Support</button>
</div>

Upvotes: 0

grorp
grorp

Reputation: 353

You've simply forgotten the closing curly bracket of the for loop.

var buttons = document.getElementsByTagName('button');

for (i = 0; i < buttons.length; i++) {
  console.log(buttons[i])
  buttons[i].onmouseenter = function() {
    console.log('hello')
  }
} //This curly bracket was missing in your code!
<div id='buttons'>
  <a href='https://discord.com/api/oauth2/authorize?client_id=775316623220277248&permissions=391232&scope=bot' target='_blank'>
    <button id='invbutton'><i class="fab fa-discord fa-3x"></i>Invite</button>
  </a>
  <button>Support</button>
</div>

Upvotes: 2

Related Questions