gene b. gene b. - 6 months ago 14
Javascript Question

Both DIV Popups Shown Instead of One

Fiddle: https://jsfiddle.net/bzrnm3y8/6/

Popup help is shown (a DIV paragraph) on clicking '?'. I got this example with the "easing" JS function, but I don't fully understand how it works.

The CSS style affects all help boxes, but I don't want all of them to open/close in unison, only the specific one that was clicked. I don't want to pin each one of these to a specific CSS style or #ID. Right now they all open up based on the CSS style.

function deselect(e) {
$('.helpbox').slideFadeToggle(function() {
e.removeClass('selected');
});
}

$(function() {
$('.helpicon').on('click', function() {
if($(this).hasClass('selected')) {
deselect($(this));
} else {
$(this).addClass('selected');
$('.helpbox').slideFadeToggle();
}
return false;
});

$('.close').on('click', function() {
deselect($('#contact'));
return false;
});
});

$.fn.slideFadeToggle = function(easing, callback) {
return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};


Any thoughts?

Answer

Your current code will obviously show both of the helpbox as you are targeting directly an class which both of the helpboxes contain , You should wrap both of the helpbox in different divs along with ? icon , and then use siblings() function from jquery to show and hide the help box for the specific ?

let say , inside a row div there are 2 elements

  • Helpbox icon
  • Helpbox text container

in this case Helpbox text container is a sibling of Helpbox icon so you can use the siblings function to make it possible by wrapping them inside a parent div

see below :

<div class="row">
    Click to show help popup overlay 1
    <a class="helpicon" href="#">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/VisualEditor_-_Icon_-_Help.svg/2000px-VisualEditor_-_Icon_-_Help.svg.png" width=15 height=15 />
    </a>
    <div class="helpbox">
        Popup #1
    </div>
</div>
<br/>
<br/>
<br/>
<div class="row">
    Click to show help popup overlay 2
    <a class="helpicon" href="#">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/VisualEditor_-_Icon_-_Help.svg/2000px-VisualEditor_-_Icon_-_Help.svg.png" width=15 height=15 />
    </a>
    <div class="helpbox">
        Popup #2
    </div>
</div>

javascript:

<script>
    $(function () {
        $('.helpicon').on('click', function () {
            if ($(this).hasClass('selected')) {
                $(this).siblings('.helpbox').slideToggle();
            } else {
                $(this).addClass('selected');
                $(this).siblings('.helpbox').slideToggle();
            }
            return false;
        });

    });
</script>

updated jsFiddle :

https://jsfiddle.net/bzrnm3y8/7/

Comments