Reputation: 125
I want to show/hide content inside li
by clicking on a link, just like the 'more information' button. The code I have hides the content of every li
, not just the clicked one. Please take a look:
$(document).ready(function() {
$('ul li').on('click', '.abrir', function(e) {
e.preventDefault();
$('ul li').find('.oculto').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
<li>
Biológica
<span class="abrir">>></span>
<span class="oculto">Texto oculto para mostrar</span>
</li>
<li>
Oxidativa
<span class="abrir">>></span>
<span class="oculto">Texto oculto para mostrar</span>
</li>
<li>
Pasificación
<span class="abrir">>></span>
<span class="oculto">Texto oculto para mostrar</span>
</li>
<li>
Dulzor
<span class="abrir">>></span>
<span class="oculto">Texto oculto para mostrar</span>
</li>
</ul>
Upvotes: 1
Views: 2113
Reputation: 489
In your script, instead of using
$('ul li').find('.oculto').toggle();
please use
$(this).parent().find('.oculto').toggle();
and also add the below code snippets with your CSS code.
.oculto { display: none; }
.abrir {
color: blue;
cursor: pointer;
}
Example right below :
***Script***
$(document).ready(function () {
$('ul li').on('click', '.abrir', function (e) {
e.preventDefault();
$(this).parent().find('.oculto').toggle();
});
});
***In CSS***
.oculto { display: none; }
.abrir {
color: blue;
cursor: pointer;
}
Upvotes: 1
Reputation: 2681
instead of this $('ul li').find('.oculto').toggle();
Just use this $(this).parent().find('.oculto').toggle();
, in your code you are hiding all the li elements not just clicked one.
Upvotes: 1
Reputation: 337743
The issue is because you're selecting all the li
elements in the click handler, not the one which contained the .abrir
element that triggered the event.
To do that, you can use the this
keyword, as jQuery sets the scope of event handler functions to be the element which raised the event. From there you can use the siblings()
method to retrieve the related .oculto
element. Try this:
$(function() {
$('ul li').on('click', '.abrir', function(e) {
e.preventDefault();
$(this).siblings('.oculto').toggle();
});
});
.oculto { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
<li>
Biológica
<span class="abrir">>></span>
<span class="oculto">Texto oculto para mostrar</span>
</li>
<li>
Oxidativa
<span class="abrir">>></span>
<span class="oculto">Texto oculto para mostrar</span>
</li>
<li>
Pasificación
<span class="abrir">>></span>
<span class="oculto">Texto oculto para mostrar</span>
</li>
<li>
Dulzor
<span class="abrir">>></span>
<span class="oculto">Texto oculto para mostrar</span>
</li>
</ul>
Upvotes: 2