Search code examples
javascriptjqueryclickparentconflict

jQuery removing parent class conflicts with its click method


I'm having some trouble with my javascript code: Theres this html:

<div class="panel02">
                <div href="#" class="settings">
                    <span><i class="q-my-account"></i> Change Settings</span>
                    <div class="form">
                        <a href="#" class="closeMenu">X</a>
                        <h3>Change City/State</h3>
                        <select name="compassToolsClockTo">
                            <option>First Option</option>
                            <option>Another Option</option>
                            <option>Another Option</option>
                            <option>Another Option</option>

                        </select>
                        <a href="#" class="submit" id="clocksSubmit">SUBMIT <i class="q-next"></i></a>
                    </div>
                </div>
                <div class="time">
                    <div class="clocks" id="clock1">
                        <i></i> 
                        <canvas id="clockFrom"></canvas>
                        <strong><span class="q-address"></span></strong>                    
                    </div>
                    <div class="clocks" id="clock2">
                        <i></i> 
                        <canvas id="clockTo"></canvas>
                        <strong><span class="q-address"></span></strong>                    
                    </div>
                </div>
            </div>

Just to explain a bit, it looks like this: Normal State

and then when you click anywhere on div.settings it'll add the "edit" class, making it look like this (nevermind it looking broken, styles aren't done yet): Edit state

Everything works fine, except when I click on the little "X" link, which is supposed to remove the edit class, hiding the form and showing the clocks again. Here's my JS code:

//settings
jQuery('.settings').click(function(e) { 
    if(!jQuery(this).hasClass('edit')) {
        jQuery(this).addClass('edit');
    }  
});
//remove edit
jQuery('.close').click(function(e) {
    e.preventDefault();
    jQuery(this).parent().parent().removeClass('edit');
});

Now this obviously conflicts, being that when I click the close button it'll also trigger the .settings event, adding the class I just removed.

Is there a better way to do this?


Solution

  • Use event.stopPropagation() to stop the event bubbling up the DOM tree.

    Also, in your HTML markup, the element has the class closeMenu, not close:

    jQuery('.closeMenu').click(function(e) {
        e.stopPropagation();
        e.preventDefault();
        jQuery(this).parent().parent().removeClass('edit');
    });
    

    More info on event bubbling.