Ajeet Ajeet - 2 months ago 6
Javascript Question

jQuery Toggle not working with multiple elements

I want to make a toggle functionality using very simple code of jQuery

On load of page temperature will be displayed in Celsius and If I clicked on that temperature text another variable holding temperate in Fahrenheit will appear.


Can anybody please help me, what mistake I am doing.

If I uncomment the
alert
function my code is working fine.


<style>#fahrenn {display:none;}</style>



document.getElementById('temprature').innerHTML='<b>Temprature: </b><span id="celcioussss">'+minTemprtr+'&#8451; </span><span id="fahrenn">'+tempFar+'&#8457;</span>';


<script>
$(document).ready(function(){
//alert();

$("#celcioussss").click(function(){
$(this).css("display","none");
$("#fahrenn").toggle();
});

$("#fahrenn").click(function(){
$(this).css("display","none");
$("#celcioussss").toggle();
});

});
</script>

Answer

It seems that you're appending HTML dynamically from JS.

If your HTML is dynamically appended in body using JS, then you need to bind the event to the particular element to make it working.

$(document).on('click', '#celcioussss', function(){
    $(this).css("display","none");
    $("#fahrenn").toggle();
});

$(document).on('click', "#fahrenn", function(){
    $(this).css("display","none");
    $("#celcioussss").toggle();
});

More information .on()