Search code examples
jqueryjquery-selectorsglobal-variablesincrementdecrement

Write to global variable with data selector


I want to write to the global variable using the data selector. Is that even possible? (Please be gentle my experience is pretty shallow :)

var one = 0;
var two = 0;
var three = 0;

$("a[data-typ]").click(function() {

  if ($(this).hasClass('active')) {

    $(this).removeClass('active');
    $(this).data("typ").toString--;

  } else {

    $(this).addClass('active');
    $(this).data("typ").toString++;

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-typ='one'>One</a>
<a data-typ='two'>Two</a>
<a data-typ='three'>Three</a>


Solution

  • Did you mean this?

    var one = 0;
    var two = 0;
    var three = 0;
    
    $("a[data-typ]").click(function() {
      const typ = $(this).data("typ")
      if ($(this).is('.active')) {
        window[typ]--
      } else {
        window[typ]++
      }
      console.log(one,two,three)
      $(this).toggleClass("active");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a data-typ='one'>One</a>
    <a data-typ='two'>Two</a>
    <a data-typ='three'>Three</a>

    If you have more than one data-typ in one attribute you need to split:

    var one = 0;
    var two = 0;
    var three = 0;
    
    $("a[data-typ]").click(function() {
      const types = $(this).data("typ").split(" "); // split on space.
      const active = $(this).is('.active');
      types.forEach(typ => { 
        if (active) {
          window[typ]--
        } else {
          window[typ]++
        }
      })
      console.log(one, two, three)
      $(this).toggleClass("active");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a data-typ='one three'>One and three</a>
    <a data-typ='two'>Two</a>