How to use javascript to achieve HTML element  hover effect?


When we develop website applications, we may need to show or hide some buttons when the mouse hovers over some elements, which is somewhat like the hover effect in css, but since we want changes the exist of elements, the setting style in css can’t achieve the purpose. We need to monitor onmouseover and onmouseout events, and write response functions to achieve the effect. The following will show how to write HTML and javascript code

Keywords: javascript , HTML , element , hover , onmouseover , onmouseout , listener.


As in the following screenshots, when the mouse hover on Act Bttuon, a piece of text is show, and when the mouse is moved out, the text is hide. 

onmouseout effect

onmouseover effect


The HTML and javascript codes to achieve the above effects are as follows.

					<!DOCTYPE html>
		<meta charset="utf-8">
		<style type="text/css">
			.middle {
				height: 100%;
				position: fixed;
				width: 100%;
				background: no-repeat center top;
				background-size: cover;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
	<body data-rsssl=1 style="background-color: #fef2ced2;">
		<div class='middle'>
			<button onmouseover="showH2()" style="position: fixed;top:30%;background-color: #ffffff;"
				onmouseout="hideH2()" type="button">Act Button</button>
			<h2 hidden="true" id='example_h2'>How to use js to control elements show and hide?</h2>
	<script type="text/javascript">
		function showH2() {
			var example_h2 = document.getElementById('example_h2');

		function hideH2() {
			var example_h2 = document.getElementById('example_h2');
			example_h2.setAttribute('hidden', true);



When developing a website, we can implement many complex hover functions by listening to the onmouseover and onmouseout events of elements, not just CSS style changes. Not only can this be used in javascript, but also in Vue.js can be achieved by listening, but in Vue.js events become @mouseover and @mouseout.

Related articles

Coming soon

If yuo have any question or need any help 

you can leave a comment or connect me with

Leave a Reply

Your email address will not be published. Required fields are marked *

Chaoxu Wei

Master student at Tongji University (Writer & Blogger)

Job hunting, both part-time and full-time jobs are accepted. Job recommendation please email me, thank you very much!


Edit Template

“There are many people in the world who want to work hard but can’t, and people who work too hard and are exhausted. Please don’t use your efforts only to chase your own victory, please use them to help others.”




Yangpu District, Shanghai