Search code examples
jqueryjquery-uijquery-ui-datepicker

jQuery UI datepicker update styles while clock running


I am using jquery ui datepicker (timer creation) along with datetimepicker customized.

I am trying to update the styles onclick of button. It is keep on resetting to default style after updating.

Expected:

enter image description here

What I am getting:

enter image description here

jsFiddle

HTML

<div class="container">
  <p>Date: <input type="text" id="datetimepicker"></p>
  <div id="clock"></div>
</div>    

<div class="btnHolder">
  <input type="button" value="Change font color" id="fontColor" />
  <input type="button" value="Change font size" id="fontSize" />
</div>

Script

$(document).ready(function(){

  $(function() {
    $( "#datetimepicker" ).datetimepicker({ 
      minDate:0,
      timeInput: true,
      timeFormat: "hh:mm tt"
    });
  });

  // on changing date initilize the countdown again
  $("#datetimepicker").change(function(){
    init($(this).val());
  })

  function init(dt){
    $('#clock').countdown(dt).on('update.countdown', function(event) {
      var $this = $(this).html(event.strftime(''
      + '<span>%-w</span> week%!w '
      +'<span>%-d</span> day%!d '
      + '<span>%H</span> hr '
      + '<span>%M</span> min '
      + '<span>%S</span> sec'));
    });
  }

  //initilize counter on load with some default date
  //init("2016/11/25");

});

jQuery(document).on('click', '#fontColor', function(){
  jQuery('#clock span').css({'color': 'red'})
})

jQuery(document).on('click', '#fontSize', function(){
  jQuery('#clock span').css({'font-size': '20px'})
})

Solution

  • You are replacing the content every second with the unstyled week, days, etc. <span>...</span>s. So even though you set the styles correctly on the spans when you click the button, it will be replaced by the unstyled content again once every second. You can set a class on the outer #clock element

    jQuery(document).on('click', '#fontColor', function() {
      jQuery('#clock').addClass('red');
    });
    

    and add the following css:

    .red > span {
      color: red;
    }
    

    > selects the direct children of the #clock.red element and sets their color to red. (More about the child combinator here.)

    Updated JSFiddle here.