Home > Software design >  Change class with data-target
Change class with data-target

Time:09-07

I have tried this:

$(".font").click(function() {
  var target = $($(this).data("target"));
  $("#text").addClass(target);
})
.pap {
  font-family: Papyrus;
}

.ar {
  font-family: Arial;
}

.hel {
  font-family: Helvetica,
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button  data-target=".pap">Papyrus</button>
<button  data-target=".ar">Arial</button>
<button  data-target=".hel">Helvetica</button>

<div id="text" >Text</div>

Unfortunately, it doesn't work to change the classes by clicking a button. Is it just a little mistake or does this logic not work at all?

CodePudding user response:

Three problems:

  1. Wrapping $(this).data("target"),
  2. Including class selector . in target dataset: data-target=".pap",
  3. Adding class rather than replacing class:

$(".font").click(function() {
  var target = $(this).data("target"); // no double $ wrap
  
  // replace class because the first class listed takes precedence
  $("#text").attr('class', target);
})
.pap {
  font-family: Papyrus;
}

.ar {
  font-family: Arial;
}

.hel {
  font-family: Helvetica,
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- notice no "dot" classname -->
<button  data-target="pap">Papyrus</button>
<button  data-target="ar">Arial</button>
<button  data-target="hel">Helvetica</button>

<div id="text" >Text</div>

  • Related