Why do we have .show() and .hide() if there is .toggle()?

Question

Why do we have .show() and .hide() if there is .toggle()?

Answer

.toggle() is an amazing method to alternate both hide and show, but it shines the brightest when we are dealing with buttons or more general a single click event. there will be times when we will like to have an element on our page for a certain amount of time only so we can set that after the document is ready a setTimeout function will run for let’s say a minute, once that minute runs we want our element to disappear, let’s take this exercise for our example:

to hide our .first-image after a minute of having our document ready we could say:

$(document).ready(() => {
   setTimeout(() => {
    $('.first-image').hide();
  }, 60000) //remember it works with milliseconds
})

now once it loads, it will count one minute and after it has passed the image will hide. We could do the same with .show(), is a common practice with those annoying popups that ask us to signup for something, or give feedback, or buy something. They usually .show() after a certain amount of time, or when our mouse hovers over a button that might lead us to leave the page. single .show() triggered is most famous in those circumstances, or with confirmation windows.

There will always be a place for .hide() and for .show() to have a solo act, yet .toggle() will mostly be king when it comes to single element click events.

5 Likes