Use attr() Function to Achieve Text Movement Effect in CSS

Introduction to the attr() Function

The CSS expression attr() is used to obtain the value of an HTML attribute of the selected element and use it for its style. attr() can also be used on pseudo-elements, and the attribute value takes the element to which the pseudo-element is attached. attr() expressions can be used with any CSS property.

attr( attr_name )

The function accepts a single parameter attr_name, which is used to hold the attribute name in the HTML element. It is a required parameter. This function returns the attribute value of the selected element.

Once you know this technique, you will be amazed at how much easier it can bring to your work! In the new version of the CSS3 standard, the attr() function has been extended to be used in various CSS tags.

How to Use attr() to Achieve Text Movement Effect

An element can have a custom attribute value, and its naming format is usually data-*attr(), which is used to obtain this custom attribute value of the element and assign it to the content of its pseudo-element as its generated content using this function. We can use pseudo-elements to "copy" another text based on the original text.

Then, we can control the text movement effect, such as moving the mouse up, the text will move. The sample code to achieve this effect is as follows.

<p class="arrt" data-text="ITCodar">ITCodar</p>
<p class="arrt" data-text="javascript">javascript</p>

<style>
	ul,li{
		list-style-type: none;
	}
	.arrt{
		display: flex;
		padding: 6px;
		color: #47cf73;
		font-size: 18px;
		text-decoration: none;
		overflow: hidden;
	}
	.arrt:hover span{
		transform: translateY(-130%);
		cursor: pointer;
	}
	.arrt span{
		position: relative;
		transition: 0.3s;
	}
	.arrt span::before{
		position: absolute;
		content: attr(data-text);
		transform: translateY(130%);
	}
</style>
<script>
	let floatText = document.querySelectorAll(".arrt");
	floatText.forEach(link => {
	  let letters = link.textContent.split("");
	  link.textContent = "";
	  letters.forEach((letter, i) => {
	    let span = document.createElement("span");
	    span.textContent = letter;
	    span.style.transitionDelay = `${i / 20}s`;
	    span.dataset.text = letter;
	    link.append(span);
	  });
	});
</script>


Leave a reply



Submit