JS: The useful trick that allows you to change text on hover

JS: The useful trick that allows you to change text on hover

ยท

3 min read

Hello World! Today I decided to write a short article on how to change text on hover. If you think this topic it's too easy... You're right, however, this article is written mainly for beginners, but I'm sure you might need it too (also because you probably googled the question)


โšก Giveaway โšก We are giving away any course you need on Udemy. Any price any course. Steps to enter the giveaway --> React to this post --> Subscribe to our Newsletter <-- Very important


How to change Text on hover with javascript:


First of all: HTML

<div class="container">
  <h1 class="title" id="title">Lorem Ipsum dolor sit amet</h1>
  <p class="text" id="text">Lorem ipsum dolor sit amet paragraph</p>

You don't really need a lot of CSS, but style is always helpful

.container {
  display: flex;
  justify-content: center;
  text-align: center;
  align-content: center;
  border: 5px solid black;
  padding: 200px 100px;
}

.text {
  font-size: 17px;
}

Last but not least, the star of the show, Javascript:

Before we start the party, let's Caching the DOM:

The results show that caching your DOM elements dramatically improves the speed of your code execution. This is clearly seen when comparing tests 3 and 4 where you get a boost from 32,889 to 602,620 operations per second. Site Point

const text = document.getElementById("text");
const title = document.getElementById("title");

We can then add an on mouse hover function: when mouse hovers text, text changes! Magic

text.onmouseover = function () {
  text.innerHTML = "I just changed cause you hovered me";
  title.innerHTML = "Please stop hovering me";
};

And on Mouse out, if we want the text to change back again

text.onmouseout = function () {
  text.innerHTML = "Lorem ipsum when mouse out";
  title.innerHTML = "";
};

In reality, you can also have this without Javascript, but it's less intuitive:

Let's start with, surprise, surprise, HTML:

  <p>
    <span class="test" data-hover="And I'm second! Even if you read me first">I'm first</span>
  </p>

And continue with CSS:

.test:hover {
  font-size: 0;
}

.test:hover:before {
  font-size: 20px;
  content: attr(data-hover);
}

You need to use attr() function... If you, like me, never heard this function before check this article on CSS tricks.

No JS this time, you happy now?


Hope this helped and thanks for reading!

Ps: Be sure to smash that like button.

You can have here a live preview (in case you missed something): Click Me


Check this article: The ultimate compilation of Cheat sheets (100+) - ๐ŸŽ / Roadmap to dev ๐Ÿš€


Subscribe to our newsletter!

A loooong, and fun, weekly recap for you Free PDF version of my articles Highly customizable inbox That's --> free <-- and you help me! Highly customizable inbox That's --> free <-- and you help me!

ย