How to create a toggle button that dynamically changes HTML content?

I have been working on this issue for several days and researched it on SO, as well as on the Internet in general, and could not find material that helped me solve it.

I am trying to create a weather application that can switch the meteorological units displayed between Fahrenheit and Celsius. I start by adding weather to Fahrenheit, and then create an event handler that conditionally changes the internal content of the related item based on whether that item currently displays β€œF” or β€œC”.

Like this, my application successfully loads with Fahrenheit temperature and switches to Celsius by click, but it does not switch to Fahrenheit. I suppose there is some problem with how events are recorded, but for life I can not understand.

Here is my code:

var fahr = document.createElement("a"); fahr.attr = ("href", "#"); fahr.className = "tempUnit"; fahr.innerHTML = tempf + "&deg;F" + "<br/>"; $("#currentWeather").append(fahr); var cels = document.createElement("a"); cels.attr = ("href", "#"); cels.className = "tempUnit"; cels.innerHTML = tempc + "&deg;C" + "<br/>"; var units = document.getElementsByClassName("tempUnit"); $(".tempUnit").click(function() { if (units[0].innerHTML.indexOf("F") != -1) { $(".tempUnit").replaceWith(cels); } else { $(".tempUnit").replaceWith(fahr); } }) 

Thank you very much! We would like to provide additional information if necessary.

+7
javascript jquery html
source share
1 answer

What you use at the moment is called direct binding, which will only attach to the element that exists on the page when your code makes an event binding call.

When you use replaceWith() , an existing element is replaced with a new element, and event handlers are not bound to them.

You need to use Event Delegation with . on () delegated events.

General syntax

 $(parentStaticContainer).on('event','selector',callback_function) 

Example. Also use this ie the context of the current element and use setAttribute() to update the href element

 $("#currentWeather").on("click", ".tempUnit", function() { if (this.innerHTML.indexOf("F") != -1) { $(this).replaceWith(cels); } else { $(this).replaceWith(fahr); } }) 

 var tempf = 212; var tempc = 100; var fahr = document.createElement("a"); fahr.setAttribute("href", "#"); fahr.className = "tempUnit"; fahr.innerHTML = tempf + "&deg;F" + "<br/>"; $("#currentWeather").append(fahr); var cels = document.createElement("a"); cels.setAttribute("href", "#"); cels.className = "tempUnit"; cels.innerHTML = tempc + "&deg;C" + "<br/>"; $("#currentWeather").on("click", ".tempUnit", function() { if (this.innerHTML.indexOf("F") != -1) { $(this).replaceWith(cels); } else { $(this).replaceWith(fahr); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="currentWeather"></div> 
+6
source share

All Articles