1

I am new to jquery so bear with me please :(

I have multiples button with css class name "one" on a page and each button is associated with another button with css class name "two".

"two" by default is set to display:none, and when "one" clicked, two is displayed. "two" will disappear when user click anywhere on the page.

I want when user clicked "one" the "two" that next to the "one" will be displayed instead of all "two" displayed.

I have the follow codes but don't know how to modify to fit my goal:

$(document).on("click", function (e) {
    var clickedElement = $(e.target);

    if (clickedElement.hasClass("one") ) {
        //$(this).next().show(400, "linear"); <--my approach....but sadly didn't work
        $(".two").show(400, "linear");
    }
    else {
        $(".two").hide();
    }
});

I made a demo in case if you want to see it :)

Andrew
  • 2,810
  • 4
  • 18
  • 32

3 Answers3

2

You were close with this line:

//$(this).next().show(400, "linear"); <--my approach....but sadly didn't work

If you change it to this it will work:

clickedElement.next(".two").show(400, "linear");
ZiNNED
  • 2,620
  • 20
  • 31
1

Try the following:

$(document).on("click", function (e) {
        var clickedElement = $(e.target);


        if (clickedElement.hasClass("one") ) {
            clickedElement.next().show(400, "linear");
        }
        else {
            $(".two").hide();
        }
    });

http://jsfiddle.net/Lwsu7ov9/3/

ltalhouarne
  • 4,586
  • 2
  • 22
  • 31
0

Based on what you described, this works:

$(document).on("click", function (e) {
    $(".two").hide();
});
$('button.one').click(function (e) {
    e.stopPropagation();
    $(this).next().show(400, "linear");
})

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
  • I saw a comment on [SO](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) about e.stopPropagation(), he said "this breaks standard behaviour of many things, including buttons and links, contained within #menucontainer". Sorry I didnt upvote yours :( – Andrew Aug 26 '14 at 14:32
  • You can replace `e.stopPropagation();` with `return false` and get the same result. – j08691 Aug 26 '14 at 14:33
  • And for the record, if used properly, `.stopPropagation()` is quite useful and safe. The link you refer to, which ends up at csstricks (don't get me started), doesn't apply to what you've posted anyway. Don't blindly write off using a function without knowing how it can be properly used. – j08691 Aug 26 '14 at 14:55