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?

szpanel
  • 39
  • 2
  • 6

2 Answers2

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'.

31piy
  • 23,323
  • 6
  • 47
  • 67
  • 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 Jan 24 '18 at 15:20
  • 1
    @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](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons). – 31piy Jan 24 '18 at 15:22
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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • `$("#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? – szpanel Jan 24 '18 at 15:32
  • Yes, although I would use the `this` reference within the event handler to save a DOM access. – Rory McCrossan Jan 24 '18 at 15:33