My desire output is to hide paragraph when user click on a button and the same button will use for hiding paragraph and change a name of the button as well.
As you can see the output in a snippet, When I click on Button then the text of the button is not changed and the paragraph is also not showing.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow", function(){
if($("#myShowHidebtn").prop('value', 'Show'))
$('#myShowHidebtn').html('Hide');
alert("The paragraph is now hidden");
});
$("#myShowHidebtn").on("click", function(){
if($("#myShowHidebtn").prop('value', 'Hide'))
$('#myShowHidebtn').html('Show');
alert("The paragraph is now hidden");
});
});
});
</script>
</head>
<body>
<button id="myShowHidebtn">Hide</button>
<p>Paragraph Containt..Paragraph Containt..Paragraph Containt..Paragraph Containt..Paragraph Containt..</p>
</body>
</html>
Firstly Html()
is incorrect. The method name is html()
.
The issue with your logic is that you're adding a new click
handler to the button
element every time it's clicked. To fix the logic simply call toggle('slow')
on the p
, and then update the text()
of the button
based on it's current setting, directly in the click handler. You can also use stop()
to prevent quick successive clicks from filling up the animation queue. Try this:
$(document).ready(function() {
$("button").click(function() {
$("p").stop(true).toggle("slow");
$("#myShowHidebtn").text(function(i, t) {
return t == 'Hide' ? 'Show' : 'Hide';
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="myShowHidebtn">Hide</button>
<p>Paragraph Containt..Paragraph Containt..Paragraph Containt..Paragraph Containt..Paragraph Containt..</p>