I'm just learning Jquery and wanted to use a button to add a "text-decoration" to a list item when clicked. The problem I have is that I can't use the same button to turn the "text-decoration" back to "none" on the second click?
Here is the Jquery code:
$(document).ready(function() {
$(".button1").click(function() {
$("ul li:nth-child(1)").css("text-decoration", "line-through");
});
});
I tried copying line 2 and 3 and changing the text-decoration to "none" within the same function but no luck.
Thanks!
Define a class in your CSS:
.stroked{ text-decoration: line-through; }
then just:
$(document).ready(function() {
$(".button1").click(function() {
$("ul li:nth-child(1)").toggleClass('stroked');
});
});
Edit: as you are learning the basics of jQuery, consider caching your selectors [if their content is not changing through page lifecycle]:
$(document).ready(function() {
var $li = $("ul li:nth-child(1)");
$(".button1").click(function() {
$li.toggleClass('stroked');
});
});
So you do not have to perform the selection on every click.
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