how to toggle attr() in jquery

Jquery

Jquery Problem Overview


I have a simple add attribute function:

$(".list-toggle").click(function() {
    $(".list-sort").attr('colspan', 6);
});

My question is: how can I turn this into a toggle, so colspan="6" is removed from the element on the next click?

Jquery Solutions


Solution 1 - Jquery

If you're feeling fancy:

$('.list-sort').attr('colspan', function(index, attr){
    return attr == 6 ? null : 6;
});

Working Fiddle

ES6 Syntax (2021):

$('.list-sort').attr('colspan', (_, attr) => attr == 6 ? null : 6));

Solution 2 - Jquery

$('.list-toggle').click(function() {
    var $listSort = $('.list-sort');
    if ($listSort.attr('colspan')) {
        $listSort.removeAttr('colspan');
    } else {
        $listSort.attr('colspan', 6);
    }
});

Here's a working fiddle example.

See the answer by @RienNeVaPlus below for a more elegant solution.

Solution 3 - Jquery

For readonly/disabled and other attributes with true/false values

$(':submit').attr('disabled', function(_, attr){ return !attr});

Solution 4 - Jquery

I know this is old and answered but I recently had to implement this and decided to make 2 simple jQuery plugins that might help for those interested

usage:

// 1
$('.container').toggleAttr('aria-hidden', "true");
// 2
$('.container').toggleAttrVal('aria-hidden', "true", "false");

1 - Toggles the entire attribute regardless if the original value doesn't match the one you provided.

2 - Toggles the value of the attribute between the 2 provided values.

 // jquery toggle whole attribute
  $.fn.toggleAttr = function(attr, val) {
    var test = $(this).attr(attr);
    if ( test ) { 
      // if attrib exists with ANY value, still remove it
      $(this).removeAttr(attr);
    } else {
      $(this).attr(attr, val);
    }
    return this;
  };
  
  // jquery toggle just the attribute value
  $.fn.toggleAttrVal = function(attr, val1, val2) {
    var test = $(this).attr(attr);
    if ( test === val1) {
      $(this).attr(attr, val2);
      return this;
    }
    if ( test === val2) {
      $(this).attr(attr, val1);
      return this;
    }
    // default to val1 if neither
    $(this).attr(attr, val1);
    return this;
  };

This is how you would use it in the original example:

$(".list-toggle").click(function() {
    $(".list-sort").toggleAttr('colspan', 6);
});

Solution 5 - Jquery

This would be a good place to use a closure:

(function() {
  var toggled = false;
  $(".list-toggle").click(function() {
    toggled = !toggled;
    $(".list-sort").attr("colspan", toggled ? 6 : null);
  });
})();

The toggled variable will only exist inside of the scope defined, and can be used to store the state of the toggle from one click event to the next.

Solution 6 - Jquery

$(".list-toggle").click(function() {
    $(this).hasAttr('colspan') ? 
        $(this).removeAttr('colspan') : $(this).attr('colspan', 6);
});

Solution 7 - Jquery

$(".list-toggle").click(function() {
    $(this).attr('colspan') ? 
    $(this).removeAttr('colspan') : $(this).attr('colspan', 6);
});

Solution 8 - Jquery

This answer is counting that the second parameter is useless when calling removeAttr! (as it was when this answer was posted) Do not use this otherwise!

Can't beat RienNeVaPlus's clean answer, but it does the job as well, it's basically a more compressed way to do the ternary operation:

$('.list-sort')[$('.list-sort').hasAttr('colspan') ? 
    'removeAttr' : 'attr']('colspan', 6);

an extra variable can be used in these cases, when you need to use the reference more than once:

var $listSort = $('.list-sort'); 
$listSort[$listSort.hasAttr('colspan') ? 'removeAttr' : 'attr']('colspan', 6);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionalias51View Question on Stackoverflow
Solution 1 - JqueryRienNeVaPlu͢sView Answer on Stackoverflow
Solution 2 - JquerymusicnothingView Answer on Stackoverflow
Solution 3 - JqueryBitOfUniverseView Answer on Stackoverflow
Solution 4 - JqueryFrancisc0View Answer on Stackoverflow
Solution 5 - JquerythirdenderView Answer on Stackoverflow
Solution 6 - JqueryZuksView Answer on Stackoverflow
Solution 7 - Jqueryuser2398069View Answer on Stackoverflow
Solution 8 - JqueryDanielView Answer on Stackoverflow