On div click reveal list item with the same class

91 Views Asked by At

I need to be able to click on a div with a certain class and have it reveal a list item with that same class. I feel like that should be simple but I'm relatively new to jQuery. I was using this:

$('.minibox').on('click', function (){
    var txt = $(this).attr('name');
    $('ul').append("<li class='list'>"+txt+"</li>");
});

but I want to do it without the append method for several reasons. I think toggleClass is probably what I'm looking for, but I'm not sure exactly how to go about using it in this context. I also want to be able to click the '.minibox' again to remove the list item, hence why I'm assuming toggleClass is what I'm looking for.

Any help is appreciated <3

2

There are 2 best solutions below

0
one stevy boi On BEST ANSWER

You can give your clicked element an attribute that points to the list element you would like to toggle. For instance if your list is like so

<ul>
    <li class="first">something</li>
    <li class="second">something else</li>
<li>

Then you can indicate on your button the class you would like to toggle like so

<button data-target-toggle="first">click me!</button>

And then your click handler could read the data from the button and use that to select the list element

$("button").click(function(){
    var targetClass = $(this).data("target-toggle");
    var targetElement = $("." + targetClass);
    //now you can do what you want to your targetElement, ie. show() or hide()
}
0
Ivijan Stefan Stipić On

The basic thing what you need:

var t = true;
$('.minibox').click(function (){
    var txt = $(this).attr('name');

    if(t==true)
    {
        $('ul').append("<li class='list'>"+txt+"</li>");
        t=false;
    }
    else
    {
        $('ul > .list').remove();
        t=true;
    }

});

But from my side you just need whole list hide and display like this:

var t = true;
    $('.minibox').click(function (){
     var txt = $(this).attr('name');

     if(t==true)
        {
            $('.ul').find('li').text(txt);
      $('.ul').show();
      t=false;
     }
     else
        {
           $('.ul').find('li').text("");
      $('.ul').hide();
      t=true;
     }
     
    });
.ul{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="ul">
<li></li>
</ul>
<a href="#" class="minibox" name="Olala man">Click</a>

That's basic.