update html content after clicking on icon

225 Views Asked by At

after clicking on the Celsius or Fahrenheit icon, i want to change the degree and the icon . What happens with me that its just updating it once.

html :

<ul id="list">
    <li></li>
    <li>&nbsp;<i class="wi wi-celsius"></i></li>
    <li></li>
</ul>

JS:

$('#list li:nth-child(2)>i').click(function() {
    var temp = $('#list li:nth-child(2)');
    if ($(this).hasClass('wi wi-celsius')) {
        alert("C");
        var convertedTemp = parseInt(temp.text()) * 9 / 5 + 32;
        temp.html(Math.round(convertedTemp) + '&nbsp;<i class="wi wi-fahrenheit"></i>');

    } else {
        alert("F");
        var convertedTemp = (parseInt(temp.text()) - 32) / (9 / 5);
        temp.html(Math.round(convertedTemp) + '&nbsp;<i class="wi wi-   celsius"></i>');
    }
});
2

There are 2 best solutions below

1
On BEST ANSWER

Because you remove the element from the page. The event does not get hooked up to the new element that you add. So you need to use event delegation.

$('#list li:nth-child(2)').on("click", ">i" , function () {

The other option is do not replace the HTML, just replace the text and classes.

$('#list li:nth-child(2)>i').click(function() {
  var icon = $(this).toggleClass("wi-celsius wi-fahrenheit"),
      li = icon.closest("li"),
      span = li.find("span"),
      num = parseFloat(span.text()),
      isCel = icon.hasClass('wi-celsius'),
      val = isCel ? num * 9 / 5 + 32: (num - 32) * 5 / 9;
  span.text(val);
});
.wi-celsius::after { 
  cursor : pointer;
  content : "°C"
}

.wi-fahrenheit::after { 
  cursor : pointer;
  content : "°F"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="list">
  <li></li>
  <li><span class="num">32</span>&nbsp;<i class="wi wi-celsius"></i>
  </li>
  <li></li>
</ul>

5
On

I would use JQuery's toggle class

$('#list li:nth-child(2)>i').click(function(){
  var temp = $('#list li:nth-child(2) > span.num');
  $(this).toggleClass("wi-celsius");
  $(this).toggleClass("wi-fahrenheit");

  if($(this).hasClass("wi-celsius")){
     var convertedTemp = parseInt(temp.text()) * 9 / 5 + 32;
  }else{
     var convertedTemp = (parseInt(temp.text()) -32)/ (9/5);    
  }

  $('#list li:nth-child(2)> span.num').text(convertedTemp);
});

This will just change them on each click.

Edit: works now by adding the span in @epascarello's answer