Hover on Elements with JavaScript

Advertisements

Hello. I want to scale the penguin on :hover like this:

#penguin {
  width: 100px;
}
#penguin:hover {
  transform: scale(1.04);
}
<img id="penguin" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/1707px-NewTux.svg.png">

But my problem is that I want to include the scale in JavaScript and not in CSS. I tried it with style.transform = 'scale(1.04)'; but it’s not working.

document.getElementById('penguin').style.transform = 'scale(1.04)';
#penguin {
  width: 100px;
}
<img id="penguin" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/1707px-NewTux.svg.png">

The reason I want to put it in JavaScript is because I have an image that acts as a button. The opacity is 10%. When an event occurs it becomes 100% and should then achieve the :hover effect.

>Solution :

It is working, it added the style correctly. However, you have to add javascript events if you want it to scale up when the mouse is hovering over the element and scale back down when it exits the element.

Also, this makes it easier if it is only supposed to do that under a condition.

document.getElementById('penguin').addEventListener("mouseout", () => { 
    document.getElementById('penguin').style.transform = 'scale(1)';
});

let condition = false;
document.getElementById('penguin').addEventListener("mouseover", () => { 
    if (condition) document.getElementById('penguin').style.transform = 'scale(1.04)';
});
document.getElementById('condition').addEventListener("click", () => { 
    condition = !condition;
});
#penguin {
  width: 100px;
}
<img id="penguin" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/1707px-NewTux.svg.png">
<button id="condition">toggle condition</button>

Leave a ReplyCancel reply