0

I would like to change fonts dynamically, But my code only behaves nicely the first time i change a font. It seems that my code remembers previous clicked buttons and adds those to be changed as well every time i select a new font for a button. My code is available at jsfiddle

function font(id,element){
  $(id).bind('change',function(){
    var fontTypeSelected = $(id).val();
    $(element).css('font-family',fontTypeSelected);
  });
}

$('#settings-ID').change(function(){
  font('#font','#' + $('#settings-ID').val());
});
         
$('.list').on('click','.settings',function(){
  // Set current row or box section ID
  $('#settings-ID').val($(this).attr('id'));
  $("#settings-ID").trigger("change");
});
.list div {
  float:left;
  padding:10px;
  background-color:#CCC;
  margin:10px 10px 0 0;
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click on one of the buttons below to change font
<div class="list">
  <div class="settings" id="1">Font one</div>
  <div class="settings" id="2">Font two</div>
</div>
<br>Selected button ID: <input type="text" id="settings-ID" placeholder="None selected"><br>
<br>
<select class="form-control" id="font">
  <option>Arial</option>
  <option>Courier</option>
  <option>Verdana</option>
  <option>Times new roman</option>
</select>

I really hope someone can help me with this problem. I'm kind of stuck here.

1 Answer 1

1

You are defining multiple change events when you call the function

Use .unbind("change") to delete the change event before defining the next one.

function font(id,element){
  $(id).unbind('change').bind('change',function(){
    var fontTypeSelected = $(id).val();
    $(element).css('font-family',fontTypeSelected);
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.