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:
- Wrapping
$(this).data("target")
, - Including class selector
.
intarget
dataset:data-target=".pap"
, - 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>