Bruno Alves
Bruno Alves

Reputation: 318

jQuery replaceWith doesn't work

In my JS I pretend to switch between fahrenheit and celsius but when I try to change html by $("#temp").replaceWith(temp) nothing happens as you can see here: https://codepen.io/brunofigalves/pen/KRWdQo/

Here is the piece of code that I'm using to do this

$(document).ready(function(){
  var lat, lon, temp;
  var isCelsius = true;

  $("#fahrenheit").click(function() {
    if(isCelsius) {
      temp = Math.round(temp*9/5 + 32);
      $("#temp").replaceWith(temp);
      isCelsius = false;
    }
    console.log(temp); 
  });
  $("#celsius").click(function() {
    if(!isCelsius) {
      temp = Math.round((temp-32)*(5/9));
      $("#temp").replaceWith(temp);
      isCelsius = true;
    }
    console.log(temp);
  });

});

Upvotes: 1

Views: 1041

Answers (1)

Nope
Nope

Reputation: 22329

You have to give temp an initial value. By default it is undefined causing your calculation to not work as expected.

While giving temp a value, fixing your NaN issue, you only can convert your value ones as (#temp).replaceWith() doesn't work as you expect. It will replace the complete element, removing it from the DOM after the first time.

See replacewith for more details.

Using $(#temp).text(temp) in this case seems to work.

I have set your initial temp below to 0 for the sake of the example. That way it switches between 0 and 32

$(document).ready(function() {
  var lat, lon, temp = 0;
  var isCelsius = true;

  $("#time").text(updateTime);

  function updateTime() {
    let d = new Date();
    var dayString = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
    return dayString[d.getDay() - 1] + ", " + d.getHours() + ":" + d.getMinutes();
  }
  $("#fahrenheit").click(function() {
    if (isCelsius) {
      temp = Math.round(temp * 9 / 5 + 32);
      $("#temp").text(temp);
      isCelsius = false;
    }
    console.log(temp);
  });
  $("#celsius").click(function() {
    if (!isCelsius) {
      temp = Math.round((temp - 32) * (5 / 9));
      $("#temp").text(temp);
      isCelsius = true;
    }
    console.log(temp);
  });


  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(updateCoordinates);
  } else {}

  function updateCoordinates(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    getWeatherInfo();
  }

  function getWeatherInfo() {
    $.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + lat + "&lon=" + lon, function(data) {
      $("#location").replaceWith(data.name + ", " + data.sys.country);
      $("#summary").replaceWith(data.weather[0].main + ", " + data.weather[0].description);
      temp = Math.round(data.main.temp);
      $("#temp").replaceWith(temp);
      updateImage(data.weather[0].description);
    });
  }

  function updateImage(forecast) {
    switch (forecast) {
      case "clear sky":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-day-sunny");
        break;
      case "few clouds":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-day-cloudy");
        break;
      case "scattered clouds":
      case "broken clouds":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-cloudy");
        break;
      case "shower rain":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-day-rain-mix");
        break;
      case "rain":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-rain");
        break;
      case "thunderstorm":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-thunderstorm");
        break;
      case "snow":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-snow");
        break;
      case "mist":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-fog");
        break;
    }
  }

});
@import "https://rawgit.com/bomholtm/fcc/master/_assets/css/weather-icons.min.css";
.jumbotron {
  background: linear-gradient(45deg, #2E3192, #1BFFFF);
  color: white;
  padding-left: 20px;
}

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

div {
  transition-property: all;
  transition-duration: 5s;
}

.container-weather {
  margin-top: 50px;
}

#img-weather {
  font-size: 80px;
  margin-left: 50px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<link rel="stylesheet" href="https://rawgit.com/bomholtm/fcc/master/_assets/css/font-awesome.min.css">
<main class="container">
  <div class="jumbotron center">
    <h1 class="display-5"><a id="location">Loading data</a></h1>
    <h2 class="lead"><a id="time">time<a/></h2>
      <h2 class="lead"><a id="summary">summary<a/></h2>
      <div class="row container-weather">
        <h2 class="display-2"><a id="temp">0<a/></h2>
        <a id="celsius" href="#">°C</a>|<a id="fahrenheit" href="#">°F</a>
      <div id="img-weather"></div>
  </div>

  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
        View more
      </button>
  <div class="collapse" id="collapseExample">
    <div class="card card-body">
      Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
    </div>
  </div>
  </div>
</main>


<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>

Upvotes: 1

Related Questions