Weather App - preventDefault only works once?

I’m trying to get the temperature switching mechanism on my weather app working properly. It does work, sort of…but not well.

I’m currently just using a plain text link to say “view in Fahrenheit” or “view in Celsius.” A jQuery statement monitors clicks on the link and toggles between the two temperature scales accordingly.

$(".switchCF").click(function(e) {
        if (displayTemp === tempF) {
          displayTemp = tempC;
        } else {
          displayTemp = tempF;
        $("#temperature").html("Temperature: " + displayTemp);

I’m trying to use the prevent default method to keep a click event from triggering a page load. This works once - the page defaults to Fahrenheit, and clicking “view in Celsius” behaves exactly as I expect it to. Once the content is refreshed, clicking the second link to toggle the display back to Fahrenheit triggers a page load. While the page refresh technically brings you back to the fahrenheit display, it’s not ideal. Any thoughts as to why this is happening?

Here’s the pen for any further context (it’s still a barebones work in progress…trying to get the functionality down before I make it pretty :slight_smile:

I briefly looked at your code, but I believe the problem is that you have:

  $(function(latitude, longitude) {

inside of your success function, so anything inside of the:

  $(function(latitude, longitude) { } 

block will only work once (when the DOM has loaded). The second time the a tag is clicked, it just acts like a normal click and since you do not specify an href, it just loads the page again. Try making the

  $(function(latitude, longitude) {

your outer function, so everything else is inside. You still may have to adjust your logic, but at least this will get you started in the right direction.

Thanks for steering me in the right direction! It took a little bit of time to unravel some of my spaghetti code, but I think I’ve settled on a decent (or at least “good enough”) solution now.

I decided to change the item being watched from an “a” link to a button, which got rid of my preventDefault() issue, then switched out the jQuery .click() for a .delegate() method, and now it works the way I’d expect it to.

Keep in mind that .delegate has been deprecated. You should use .on instead.

Instead of:

$("#localWeather").delegate(".switchCF", "click", function() {

use the following instead:

$("#localWeather").on("click",".switchCF", function() {

Thanks again - yet another reason it’s important to pay attention to posting dates when reading Stack Overflow…