JQuery event handlers not firing
Look at my code -
Html
<table>
<tr>
<td valign="top" style="padding-top:10px;">Body :<br><br>
<a id="expand" href="javascript:;">expand</a>
</td>
<td>
<textarea rows="6" cols="30" required="required" id="message" name="message">
</textarea>
</td>
</tr>
</table>
JQuery
$(function(){
$("#expand").click(function(){
$('#message').animate({"height": "300px"}, "slow" );
$(this).attr('id','colaspe').html('colaspe');
return false;
});
$("#colaspe").click(function(){
$('#message').animate({"height": "80px"}, "slow" );
$(this).attr('id','expand').html('expand');
return false;
});
});
My above code works when clicked expand
. But it colaspe
doesn't work.
JSFIDDLE
source to share
Try the following:
$(document).on('click','#expand',function(){
$('#message').animate({"height": "300px"}, "slow" );
$(this).attr('id','colaspe').html('colaspe');
return false;
});
$(document).on('click','#colaspe',function(){
$('#message').animate({"height": "80px"}, "slow" );
$(this).attr('id','expand').html('expand');
return false;
});
Cause: Attributes and properties are dynamically changing. For such elements, there is a function .on
to bind events to an element in jQuery. Therefore, you need to use a function .on
with an element.
source to share
It is incorrect to always change the identifier. Try using the class instead .
<table>
<tr>
<td valign="top" style="padding-top:10px;">Body :<br><br>
<a id="control" href="javascript:;" class="expand">expand</a>
</td>
<td>
<textarea rows="6" cols="30" required="required" id="message" name="message"></textarea>
</td>
</tr>
</table>
<script>
$("#control").click(function(){
if ($(this).hasClass('expand')) {
$('#message').animate({"height": "300px"}, "slow" );
$(this).removeClass('expand').addClass('colapse').html('colapse');
} else if ($(this).hasClass('colapse')) {
$('#message').animate({"height": "80px"}, "slow" );
$(this).removeClass('colapse').addClass('expand').html('expand');
}
return false;
});
</script>
source to share
this is happening because the id is missing when you apply the event
$(document.body).on('click', '#expand', function () {
$('#message').animate({
"height": "300px"
}, "slow");
$(this).attr('id', 'colaspe').html('colaspe');
return false;
});
$(document.body).on("click", '#colaspe', function () {
$('#message').animate({
"height": "80px"
}, "slow");
$(this).attr('id', 'expand').html('expand');
return false;
});
user Script here
source to share
You are replacing the current ID of a button that doesn't work.
$("#toggle").click(function(){
if ($(this).attr('class') === 'expand'){
$('#message').animate({"height": "300px"}, "slow" );
$(this).attr('class','colaspe').html('colaspe');
}
else {
$('#message').animate({"height": "80px"}, "slow" );
$(this).attr('class','expand').html('expand');
}
});
Have a look at this fixed fiddle
source to share