I am trying to change the font size of a webpage. I have specified three sizes:
Based on what the user clicks the html font size should become the size he chooses.
#small
, #med
, #large
are three paragraph elements.
medium
, small
, large
are three classes for CSS.
My code is:
enter code here
<script>
$(document).ready(function(){
$("#small").click(function(){
if($("p").hasClass('large'))
{
$("p").removeClass("large").addClass("small");
}
else
{
$("p").removeClass("medium").addClass("small");
}
});
$("#med").click(function(){
if($("p").hasClass('small'))
{
$("p").removeClass("small").addClass("medium");
}
else
{
$("p").removeClass("large").addClass("medium");
}
});
$("#large").click(function(){
if($("p").hasClass('small'))
{
$("p").removeClass("small").addClass("large");
}
else
{
$("p").removeClass("medium").addClass("large");
}
});
});
</script>
I don't think its working perfectly. So if anyone could show where i am going wrong will be of great help.
You are a bit verbose, for each click there is no need for any decision, you always have to remove any of the other two classes and add the one from the button you pressed
$(document).ready(function(){
$("#small").click(function(){
$("p").removeClass("medium").removeClass("large").addClass("small");
});
$("#med").click(function(){
$("p").removeClass("small").removeClass("large").addClass("medium");
});
$("#large").click(function(){
$("p").removeClass("small").removeClass("medium").addClass("large");
});
});
You could probably "compress" that further by using the id
as a variable using something like the following (note that the click-able element is "#med" and the class is "medium", so that would need additional work)
$(document).ready(function(){
$("#small,#med,#large").click(function(this){
$("p").removeClass().addClass($(this).attr("id"));
});
});