Collins Orlando
Collins Orlando

Reputation: 1681

How do I revert back to default values in HTML/DOM after triggering an event(jQuery)?

How do I go back and fro i.e switch to Celsius upon clicking the button, then reverting back to Fahrenheit when I click again? Surely it should not be this hard, but I am missing something here.

Here are the relevant codes:

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Ancient</title>
</head>
<body>
    <h1><span id="temp1">-40</span> &deg;<span class="units">F</span></h1>
    <p><span id="temp2">-28</span> &deg;<span class="units">F</span></p>
    <button>Show Celsius</button>
    <script
      src="https://code.jquery.com/jquery-3.1.1.js"
      integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
      crossorigin="anonymous">
    </script>
    <script 
      src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" 
      integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" 
      crossorigin="anonymous">
    </script>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script src="fahtocels.js" type="text/javascript"></script>
</body>
</html>

jQuery

$(function() {
    let $temp1 = Number($("#temp1").text()),
        $temp2 = Number($("#temp2").text()),
        $units = $(".units").text();

    function fahrToCels(F) {
        return ((5/9) * (F - 32)).toFixed(2);
    }

    $("button").on("click", function() {
        $(this).html("Show Fahrenheit")
        $("#temp1").html(fahrToCels($temp1));
        $("#temp2").html(fahrToCels($temp2));
        $(".units").html("C");
    });
});

Upvotes: 0

Views: 156

Answers (3)

Nathan Hase
Nathan Hase

Reputation: 659

You'll need to store these values in variables. They can be attached directly to the window for a quick POC, but the best practice is to enclose your behavior in a closure to maintain the integrity of the data.

something like:

// IIFE to create a closure
// $ will be window.jQuery
// sample will be window.sample
// undefined will be an object that is undefined (so you can compare it like null without doing typeof
(function ($, sample, undefined) {
    // add a namespace for the behavior in this closure
    var ns = sample.namespace || (sample.namespace = {});

    var settings = {
        setting: "defaultvalue"
    };

    // attach a named function expersson to the namespace
    // outside of this closure this will be available at window.sample.namespace.handleButtonClick();
    ns.handleButtonClick = function(){
        console.log(settings.setting);
    };

    // document ready
    $(function() {
        // code in here will have access to the ns alias and the settings object
    });

})(window.jQuery, window.sample || (window.sample = {}));
// passing in jQuery and something to attach to the window (window.sample will either be the existing instance of window.sample or a new object)

Upvotes: 1

Neil
Neil

Reputation: 14313

This is capable of converting back and forth between celcius and faherenheit. What you were missing was a function to convert it back, along with a check to see what the current unit is. This version fixes that.

$(function() {
    let $temp1 = Number($("#temp1").text()),
        $temp2 = Number($("#temp2").text()),
        $units = $(".units").text();

    function fahrToCels(F) {
        return ((5/9) * (F - 32)).toFixed(2);
    }

    function celsToFahr(C) {
        return (C * 9/5 + 32).toFixed(2);
    }

    $("button").on("click", function() {
        if ($(".units").html() === "C") {
            $(this).html("Show Celcius")
            $("#temp1").html(celsToFahr($temp1));
            $("#temp2").html(celsToFahr($temp2));
            $(".units").html("F");
        } else {
            $(this).html("Show Fahrenheit")
            $("#temp1").html(fahrToCels($temp1));
            $("#temp2").html(fahrToCels($temp2));
            $(".units").html("C");
        }
    });
});

Upvotes: 2

Brandon
Brandon

Reputation: 3266

You want to have a sort of toggle functionality. I'd store the current unit within a button like this <button id="js-hook" data-current="F">Unit Toggle</button>.

Then on my click event listener run a switch on it like so:

$("#js-hook").click(function() {

  var currentUnit = $(this).attr("data-current");
  switch (currentUnit) {

    case "F":
      // calculate celsius then swap data value
      $(this).attr("data-current", "C");
      break;
    case "C":
      // calculate fahrenheit then swap data value
      $(this).attr("data-current", "F");

  }

});

Basically, every time you click the button, it reads the current metric and if it's currently C, we run our calculation and then set it to F, etc.

JSBIN DEMO: http://jsbin.com/kafewikece/edit?html,js,console,output

Upvotes: 1

Related Questions