How to create blinking cursor effect using Javascript.

Bharat Gupta
1 min readDec 16, 2018

--

Overview

A tutorial for creating blinking cursor.

Procedure

We will first write HTML, CSS and Javascript step by step.

Basic HTML
Create a span tag that will contain the cursor. Give the span an id of cursor for referencing it in CSS and Javascript.

<html>
<head>
</head>
<body>
<span id="cursor">|</span>
</body>
</html>

CSS
Increase font size to make cursor more visible.

<html>
<head>
<style>
#cursor{
font-size: 30px;
}
</style>

</head>
<body>
<span id="cursor">|</span>
</body>
</html>

Javascript

<html>
<head>
<style>
#cursor{
font-size: 30px;
}
</style>
</head>
<body>
<span id="cursor">|</span>
<script>
var cursor = true;
var speed = 250;
setInterval(() => {
if(cursor) {
document.getElementById('cursor').style.opacity = 0;
cursor = false;
}else {
document.getElementById('cursor').style.opacity = 1;
cursor = true;
}
}, speed);
</script>

</body>
</html>

setInterval(function, time) method executes function repetitively after given time in milliseconds.

document.getElementById('cursor').style.opacity = 0 this line is used to change Opacity CSS property using Javascript and DOM.

Conclusion

Basic example of HTML, CSS, Javascript. It can be done using jquey as well.

--

--

Bharat Gupta

Software Engineer. React | React Native | Next.js | PHP | Laravel