user1325194
user1325194

Reputation: 175

JQuery function doesn't fire on first click, but behaves as expected on all subsequent clicks

I simply need the selected link to show as selected and to show the indicated div while hiding the other two. Here's the jsfiddle:

http://jsfiddle.net/HZ4CZ/1/

Why is it not working the first click, but working every click after that?

$(document).ready(function() {
    $('ul#chooseType li a').click(function(e) {   
        $('#active').click(function(){
            $('.activeDiv').removeClass('show_hide');
            $('.inactiveDiv').addClass('show_hide');
            $('.thirdMenuDiv').addClass('show_hide');
            $('#active').addClass('selected');
            $('#inactive').removeClass('selected');
            $('#thirdMenu').removeClass('selected');
        });
        $('#inactive').click(function(){
            $('.activeDiv').addClass('show_hide');
            $('.inactiveDiv').removeClass('show_hide');
            $('.thirdMenuDiv').addClass('show_hide');
            $('#active').removeClass('selected');
            $('#inactive').addClass('selected');
            $('#thirdMenu').removeClass('selected');
        });
        $('#thirdMenu').click(function(){
            $('.activeDiv').addClass('show_hide');
            $('.inactiveDiv').addClass('show_hide');
            $('.thirdMenuDiv').removeClass('show_hide');
            $('#active').removeClass('selected');
            $('#inactive').removeClass('selected');
            $('#thirdMenu').addClass('selected');
        });

    });
});

Upvotes: 2

Views: 10718

Answers (4)

Displee
Displee

Reputation: 720

I was importing bootstrap in one of my components like this:

import 'bootstrap/dist/js/bootstrap.bundle.min.js';

It turned out it was not needed to import bootstrap at all.

Upvotes: 0

Barmar
Barmar

Reputation: 780724

Add a class display to all the DIVs that are used to display the tab contents. Then use DRY code like this:

$(document).ready(function() {
    $('ul#chooseType li a').click(function(e) {  
        $('ul#chooseType li a').removeClass('selected');
        $(this).addClass('selected');
        $('.display').addClass('show_hide');
        $('.display.'+this.id+'Div').removeClass('show_hide');
    });
});

FIDDLE

Upvotes: 0

Scheintod
Scheintod

Reputation: 8105

You're installing one click handler 'ul#chooseType li a' which - when clicked - installes the other click handlers. Just remove it and it should work: http://jsfiddle.net/HZ4CZ/12/

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Dont nest your click handlers! Get rid of that all encompassing handler and you're set. Fiddle: http://jsfiddle.net/tymeJV/HZ4CZ/2/

Axe this handler: $('ul#chooseType li a').click(function(e) {

It works because none of your click handlers actually get bound on page load, they get bound after the initial click.

Upvotes: 6

Related Questions