I am dynamically altering the class of a div when ajax request completes.
<div id="MyDiv1" class="oldclass">Age</div>
Inside the success function of ajax request :
$('.oldclass').click({ alert('I am old'); });
$('.youngclass').click({ alert('I am young'); });
$.ajax({
........
success: function(){
$('#MyDiv1').removeAttr('oldclass');
$('#MyDiv1').addAttr('youngclass');
}
});
But still the click oldclass click is working on clicking this div. How do I achieve this without refreshing the whole page.
You are using attr when you mean class.
You do need to delegate since you cannot access the element after you change the class otherwise
$(() => {
// here we delegate from the nearest STATIC container
$('#container').on('click', '.oldclass', function() {
alert('I am old');
});
$('#container').on('click', '.youngclass', function() {
alert('I am young');
});
setTimeout(() => {
$('#MyDiv1').removeClass('oldclass');
$('#MyDiv1').addClass('youngclass');
}, 5000); // click again in 5 seconds
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="container">
Click, wait 5 secs and click again
<button id="MyDiv1" class="oldclass">Age</button>
</div>
DRYer:
$(() => {
// here we delegate from the nearest STATIC container
// if you do NOT replace the button in the DOM you can use $('#MyDiv1').'click', function() {
$('#container').on('click', '#MyDiv1', function() { // clicking the button
alert(`I am ${$(this).is('.youngclass') ? 'young':'old'}`);
});
setTimeout(() => {
$('#MyDiv1').removeClass('oldclass');
$('#MyDiv1').addClass('youngclass');
}, 5000); // click again in 5 seconds
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="container">
Click, wait 5 secs and click again
<button id="MyDiv1" class="oldclass">Age</button>
</div>