Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: How to remove strikethrough on second click?

Tags:

jquery

css

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!

like image 278
Ali Avatar asked Dec 01 '22 17:12

Ali


1 Answers

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.

like image 108
moonwave99 Avatar answered Dec 23 '22 03:12

moonwave99