You could probably encapsulate all that in a function and call the function three times. It would arguably be a slightly worse solution.
You could create a more generic event whenever the tag count is updated. This event is triggered from
remove. This event will read the current tag count and display it.
You could encapsulate all this in an object
RemainingTags which has
Remove methods and can automatically display the counter. Additionally you could sepparate the view from the model so
RemainingTags just keeps the logic and
RemainingTagsView will create the associated HTML based on an event triggered by
RemainingTags so everything is decoupled.
But really, is it worth it? Why go so great lengths? DRY is a nice principle, especially when having a complicated logic or big code bases. But for 15 lines of code from which 3 are duplicated, with a good reason, why use DRY?
The only logic you would encapsulate would be the addition
tagsLeftTmp + ' of ' + tagsLimit + ' tags left' so one could argue that maybe it is better to put all this in a function. Something like
I would argue that the code is best in this state. It is simple enough, it is clear, don't over-engineer it. Take a note or left a comment if you feel like wanting to ensure it will be refactored if it will increase in complexity. But take the refactoring decision then, not now, so you can pick the best solution for that situation!.
What if you create a generic way of displaying that message and then you decide you want to change the color to red when you have one tag left. But then some users will have a bigger tag limit and there will also be automatically added tags by the application which will not count toward this limit, except when the automatically added tag is a tag taken from the user preference in which case it must count. And the color should be bright green if there is no tag currently set but should not color at all for mobile because it ruins the UI there.
You get the point. Don't solve a problem you don't have.