Ardit Mata Ardit Mata - 9 months ago 20
Javascript Question

How do i apply a function to only a specific div in a collection of divs generated by foreach loop?

When i click on SHOW MORE in one of the divs generated, in every div the footer div shows up with options Test1, Test2. I want the function to apply to the div im clicking on only. Help please :(

@foreach ($articles as $article)

<div class="row">
<div class="panel-heading">{{$article->title}}</div>
<div class="panel-body">{{$article->content}}</div>

<div class="panel-footer">
<div class="more" onclick="showPortals()">
Show More</div>
<div class="other_sources">Other Sources:
<a href="">Test 1</a>,
<a href="">Test 2</a>
<span class="less" onclick="hidePortals()">Show Less</span>
</div>
</div>
</div>

@endforeach
<script>
function showPortals() {
$(".other_sources").show();
$(".more").hide();
}
function hidePortals() {
$(".other_sources").hide();
$(".more").show();
}
</script>

Answer Source

You can access the object you’re clicking via this object. You can pass it to your function:

<div class="more" onclick="showPortals(this)">

<span class="less" onclick="hidePortals(this)">Show Less</span>

Once you have the object representing your element (here, it will be div and span respectively), you can wrap it inside $ to get a jQuery object. Then, you can use .closest('.panel-footer') on the jQuery object to get your panel footer, and .find(selector) to find relevant objects inside the current panel-footer:

    function showPortals(clickedElement) {
        var $panelFooter = $(clickedElement).closest('.panel-footer');
        $panelFooter.find(".other_sources").show();
        $panelFooter.find(".more").hide();
    }
    function hidePortals(clickedElement) {
        var $panelFooter = $(clickedElement).closest('.panel-footer');
        $panelFooter.find(".other_sources").hide();
        $panelFooter.find(".more").show();
    }

However, onclick="hidePortals(this)" is not a recommended way of doing things because you’re mixing JavaScript with HTML. Instead, it’s recommended that you remove onclick="..." handlers and use jQuery’s .click handler, like this:

<script>
$(function() {
    $('.more').click(function () {
        var $panelFooter = $(this).closest('.panel-footer');
        $panelFooter.find(".other_sources").show();
        $panelFooter.find(".more").hide();
    });
    $('.less').click(function () {
        var $panelFooter = $(this).closest('.panel-footer');
        $panelFooter.find(".other_sources").hide();
        $panelFooter.find(".more").show();
    });
});
</script>