Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hover on Elements with JavaScript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading