Advance jquery show/hide with multiple div

Hi everyone, me again. So right now I am coding a jqeury which show an hide specific divs. to make it clear this should be the outcome:

so the red small box is my button. when I click it the item link to it would show. this is my code so far:

<script type="text/javascript">
$( document ).ready(function() {`$(function() {`
$('#showdiv1').click(function() {
$('div[id^=div]').hide();
$('#div1').fadeIn(3000);
 $('#div1').show();
});
$('#showdiv2').click(function() {
$('div[id^=div]').hide();
    $('#div2').fadeIn("slow");` $('#div2').show();
});`});
});
</script>

I got this code from other source an found it good. But when I make some test. I notice som problems. this what happen. when I click multiple times on the button there is a chance that two div boxes will show like this:

Do you mind tossing this into a http://JSFiddle.net or showing the HTML? You have a lot of weirdness going on with that snippet. Until you response, here are some pointers:

$( document ).ready(function() {
and
$(function() {

are equivalent (they both run when the document is ready), so there is no need to nest them like you do.

Secondly, the $('#divX').show() after the fadeIn() is unnecessary since the element will be shown after. In fact, it’ll trump the animation and actually just pop in instead of animating (it’s actually worse than that, because the animation cycles will still be running in the background even though the element is fully shown).

Basically, what you want up there is actually this:

$(function() {
    $('#showdiv1').click(function() {
        $('div[id^=div]').hide();
        $('#div1').fadeIn(3000);
    });
    $('#showdiv2').click(function() {
        $('div[id^=div]').hide();
        $('#div2').fadeIn("slow");
    });
});

That actually should work fine, so until I see the fiddle or the HTML I can only assume you have duplicate ID’s in the HTML.

Hi there! first, thank you so much for helping me. here’s the fiddle: [http://jsfiddle.net/Saiha/0m2b8wqm/][1]

[1]: http://jsfiddle.net/Saiha/0m2b8wqm/ . I couldn’t make it work this time. I don’t know what’s wrong?

Whoops, you have to add jQuery in the sidebar too:

That’s all that was missing (I’ve updated it): ! http://jsfiddle.net/0m2b8wqm/1/

Oh yeah, I was rushing to do the code to show you. It is now working okay. Thank you so much men! I’m gonna give it a shot now in my website. :smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.