0
$("#button_announcement").click(function(){ 
    $('#button_announcement').html('Hide') ? $(this).html('Show') : $(this).html('Hide');
});

I have a button on my page which show/hide my announcement. I wanted to change button html after clicking it but this code change just once from 'hide' to 'show' it don't want to change from show to hide... What am I doing wrong?

1
  • .html('Hide') will always set the HTML to Hide. It won't retrieve the HTML Commented Jan 24, 2018 at 15:18

2 Answers 2

1

Change this:

$('#button_announcement').html('Hide') ? ...

to this:

$('#button_announcement').html() === 'Hide' ? ...

The former just assigns 'Hide' as the HTML always, but the latter checks if the HTML of #button_announcement is 'Hide'.

Sign up to request clarification or add additional context in comments.

2 Comments

It works when i change just condition. $('#button_announcement').html() === 'Hide' Should I change the rest of the code similar to this? And another question. Why did you use three characters equals? Im new in jquery and as i remember in JS i never used '==='.
@szpanel -- 1) Yes, you will have to use such code at every place where you want such work. Please look at Rory's answer as well because it is quite efficient. 2) Have a look at this discussion.
1

The issue is because you're using the setter of html() in the condition. You need to use the getter and check the value instead. Note that using the text() method here would be better practice:

$("#button_announcement").click(function(){ 
    $(this).text() == 'Hide' ? $(this).text('Show') : $(this).text('Hide');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button_announcement">Hide</button>

Alternatively you can provide a function to text() which updates the value based on its current setting. This avoids the need for the explicit getter:

$("#button_announcement").click(function() {
  $(this).text(function(i, t) {
    return t == 'Hide' ? 'Show' : 'Hide';
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button_announcement">Hide</button>

2 Comments

$("#button_announcement").click(function(){ $('#button_announcement').text() == 'Hide' ? $(this).text('Show') : $(this).text('Hide'); }); $("#button_announcement").click(function(){ $('#button_announcement').html() === 'Hide' ? $(this).html('Show') : $(this).html('Hide'); }); Thank you. Just ask, both are correct?
Yes, although I would use the this reference within the event handler to save a DOM access.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.