Reputation: 61
I have a time variable that updates and want to restart its value only when you mouse over on a different element, if you hover on the same element it should keep updating. How should I approach this? Here's part of the code:
// Change shaders
function changeShader() {
const elements = document.querySelectorAll('.caption');
elements.forEach(element => {
element.addEventListener('mouseover', function() {
if (you hovered on the same element) {
console.log('you moused over the same element');
} else {
console.log('you moused over on a different element');
}
});
});
}
Upvotes: 2
Views: 84
Reputation: 3832
This is one way to do so dynamically with JavaScript. In this example, the code assigns a handler to the onmouseover event of each element, in this case each element is a button.
var flags = new Array(2);
flags[0] = 0;
flags[1] = 0;
var buttons = document.getElementsByTagName("button");
for (let i = 0, max = buttons.length; i < max; i++) {
let temp = i;
buttons[temp].onmouseover= function(){
console.log("Moused over this button " + buttons[temp].id + " " + flags[temp]++ + "x before." );
if ((flags[temp] == 2)) {
this.onmouseover = null;
alert("Done documenting bbutton " + buttons[temp].id);
}
};
}// end for
<style>
#a {
background: #000;
color: lime;
}
#b {
background: #000;
color: cyan;
}
#a:hover,#b:hover {
background: #600;
color: #ffdede;
}
</style>
<div><button id="a">Button A</button>
<button id="b">Button B</button></div>
By setting each button with a unique id attribute, it uses that value to distinguish which button is being moused over.
Note: the CSS is strictly optional -- just wanted to enhance the visuals.
Upvotes: 1
Reputation: 1497
You can save last hovered dom and check if it's the same:
function changeShader() {
let last_hover;
const elements = document.querySelectorAll('.caption');
elements.forEach(element => {
element.addEventListener('mouseover', function() {
if (last_hover == this) {
console.log('you moused over the same element');
} else {
console.log('you moused over on a different element');
}
last_hover = this;
});
});
}
changeShader()
.caption, .no-hover{
padding:10px;
margin-bottom: 25px;
background-color: #ccc;
cursor: pointer;
}
<div class="caption">I am Caption 1</div>
<div class="caption">I am Caption 2</div>
<div class="caption">I am Caption 3</div>
<div class="caption">I am Caption 4</div>
<div class="caption">I am Caption 5</div>
Upvotes: 3