user262430
user262430

Reputation: 229

How to add a class with focus and click but not have the function run twice?

I am fairly new to jQuery and teaching my self. Below you will see the code I am working on and an included JSFiddle.

What I am looking to do is add a class when I focus on an input/select and also have the class added when I click on the parent div. I basically have it working but in 2 separate functions.

Issues:

  1. When I click on the input it adds the class but then when I click on the parent div it runs the other function and vice versa.

Possible solutions:

  1. Combine everything into one function.
  2. Say something like if class exists do not run other function.

Please explain the code so I can learn from this. If you do not have a solution any hints or direction would also be helpful. Thanks in advance!

http://jsfiddle.net/q90tue8L/

HTML

<div class="panel">
    <input type="text"/>
</div>

<div class="panel">
    <input type="text"/>
</div>

<div class="panel">
    <input type="text"/>
</div>

CSS

.panel{
    padding:15px;
    background:grey;
    margin-bottom:15px;
}

.panel-primary{
    margin:0 15px 0 15px;
    background:blue;
    margin-bottom:15px;
}

jQuery

$(document).ready(function () {

    $('.panel').click(function () {
        $('.panel').removeClass('panel-primary');
        $(this).addClass('panel-primary');
    });

    $('input, select').bind('focus blur', function () {
        $(this).closest(".panel").toggleClass('panel-primary');
    });

});

Upvotes: 0

Views: 129

Answers (1)

empiric
empiric

Reputation: 7878

You can try something like this:

$('input, select').bind('focus blur', function (event) {
    event.stopPropagation();
    $('.panel').removeClass('panel-primary');
    $(this).closest(".panel").addClass('panel-primary');
});

for your second function.

With .stopPropagation() you prevent the click event to "bubble" up the DOM. So it now never reaches the parent div to trigger your first function.

DEMO

Upvotes: 2

Related Questions