Today I've been looking for the best way to toggle the text of a button when clicked, for example from "Read more" to "Read less".
I came across this article on CSS Tricks https://css-tricks.com/swapping-out-text-five-different-ways/ regarding swapping out text and after deconstructing each of the methods I have a simple question regarding the behaviour of data attributes with JavaScript.
consider the following code:
$("button").on("click", function() {
var el = $(this);
if (el.text() == el.data("text-swap")) {
el.text(el.data("text-original"));
} else {
el.data("text-original", el.text());
el.text(el.data("text-swap"));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="example-two" data-text-swap="Show">Hide</button>
My question relates to the use of "text-original" which is a data attribute that doesn't exist in the HTML markup. How is this code not throwing an error? I'm assuming that it works because JavaScript must somehow revert to the default html which is "Hide". Can somebody explain why this works?
Generally, JS doesn't error when directly accessing non-existent properties/attributes.
Specifically, you're using jQuery's global data cache, which integrates HTML5 data- attributes, and also doesn't complain when data doesn't already exist.
Either way, that technique is unnecessary because you don't need separate storage to do this, and modern browsers make it especially easy to get data attributes via the dataset property.
This demo uses dataset and destructuring assignment to make this code very short and clean.
$("button").on("click", function() {
[this.dataset.textSwap, this.textContent] = [this.textContent, this.dataset.textSwap];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="example-two" data-text-swap="Show">Hide</button>
And of course you can do this without the jQuery dependency.
document.querySelector("button").addEventListener("click", function() {
[this.dataset.textSwap, this.textContent] = [this.textContent, this.dataset.textSwap];
});
<button id="example-two" data-text-swap="Show">Hide</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With