Zak
Zak

Reputation: 7515

JQuery .show() and .hide()?

This is a question for the facts on .hide() and .show(). This is a dumbed down version of my code, but it explains it in generality. Since it is code that has already been built, and I am changing and adding to it, I do not want to go back through and change everything to .toggle().

Imagine that you have button 1 that is ALWAYS a .show() and button 2 is ALWAYS a .hide().

Is there any need for an IF statement? Are there any implications in NOT using the IF statement? Are there any implications if you DO use an IF statement?

$('#button1').click(function() {
if (!$("#widget").is(':visible')) { 
  $('#widget').show('fast');
}
});
$('#button2').click(function() {
if ($("#widget").is(':visible')) {  
  $('#widget').hide('fast');
}
});

OR would a direct change suffice? ::

$('#button1').click(function() {
  $('#widget').show('fast');
});

$('#button2').click(function() {
  $('#widget').hide('fast');
});

I've been told that there are potential issues if said IF statement is not used. What are the potential problems involved?

Upvotes: 0

Views: 288

Answers (2)

SpYk3HH
SpYk3HH

Reputation: 22570

The second way is near fine. However, to deal with "fast clicking" issue you may want to consider jQuery's .stop() or .clearQueue() functions as they will stop any previous animation and continue with the new one.

Something like:

$('#button1').click(function() {
    $('#widget').stop().show('fast');
});

$('#button2').click(function() {
    $('#widget').stop().hide('fast');
});

The big dif between the two functions is that clearQueue is meant for stoping more than animations (callback functions, listing methods, etc...). .stop() should be all you need in this case, altho you may want to test it in different browsers enabling the different parameters (.stop(false, true) ...) and see how it functions in each browser and adjust it to your needs.

Upvotes: 2

mikeswright49
mikeswright49

Reputation: 3416

The second method is fine as mentioned in pst's answer it will work fine, and in answer to pst's question fast clicking will have no effect as it will know that it has been displayed and just return false this avoiding any fails.

Upvotes: 0

Related Questions