Jamie Carl
Jamie Carl

Reputation: 1204

jQuery not hiding DIVs if jQuery.show() used in previous event

Ok, I'm usually pretty good with jQuery but this one is doing my head in.

Basically I have a click event that hides a single DIV (a placeholder), then shows two other DIVs (an input section and control buttons section). Then, when I click on one of the control buttons to change the main DIV being shown (by hiding all the divs then showing the one I want), the hide() does not thing.

This is kind of hard to explain, so I have a jsFiddle that shows the problem at: jsFiddle

In the fiddle, what should happen is when you click the "CLICK ME" text, it should set up the DIVs correctly. Then clicking the boxes (1,2 or 3) it should change the text to "Item 1", "Item 2" or "Item 3". As you can see, the "Item 1" DIV is never hidden because this is the DIV that was shown in the initial layout event. If you comment out line #5 in the JavaScript everything works exactly as it should however the initial layout is incorrect (I'd like "Item 1" to be displayed by default).

Obviously this is a massively simplified version of what I'm actually working.

Has anyone come across this and know what the problem is?

Some code:

HTML:

<div id="newinput">
<div class="inputmode">
    <div class="placeholder">CLICK ME</div>
    <div class="modeitem item1">Item 1</div>
    <div class="modeitem item2">Item 2</div>
    <div class="modeitem item3">Item 3</div>
</div>
<div class="controls">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
</div>

JavaScript:

$('#newinput').click(function () {
    var im = $(this).children('.inputmode');
    var ph = im.children('.placeholder').html();
    im.children('.placeholder').hide();
    im.children('div.item1').show();
    $(this).children('.controls').show();
});

$('#newinput .controls .item').click(function () {
    var item = 'item' + $(this).html();
    var im = $('#newinput').children('.inputmode');
    im.children('div').hide();
    im.children('.modeitem.' + item).show();
});

Upvotes: 0

Views: 111

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

It is because of event propagation, when the .item is clicked it triggers the #newinput click handle also.

As a solution register the first handler only to the placeholder element

$('#newinput .inputmode .placeholder').click(function () {
    var im = $(this).closest('.inputmode');
    var ph = im.children('.placeholder').html();
    im.children('.placeholder').hide();
    im.children('div.item1').show();
    im.next('.controls').show();
});

$('#newinput .controls .item').click(function (e) {
    var item = 'item' + $(this).html();
    var im = $('#newinput').children('.inputmode');
    im.children('div').hide();
    im.children('.modeitem.' + item).show();
});

Demo: Fiddle

Upvotes: 1

Related Questions