Paramone
Paramone

Reputation: 2724

Use the same ID as the button's ID

I've been trying to make it so that whenever I click inside of a div with id="slide$i" that the clicked div should expand or collapse, depending on current form.

This a screenshot of how it looks like.

enter image description here

So basically if I click in the area of the first div (From Magazijn To Guidion) it should expand and show additional information. But we'll keep it simple for now and just try to get the divs to move at all.

My code is like this.

  $i = 0;
foreach($stock_history as $history){
    echo " 
    <div id='slide" . $i . "' >
        <p>Date: <strong> " . $history->create_date . "</strong> </p> 
        <p>To: <strong> " . $history->toLocation->name . " </strong> </p> 
        <p>From: <strong> " . $history->fromLocation->name . " </strong> </p>
        <p>Moved by:  <strong> " .  $history->user->username . " </strong> </p>
        <hr />
    </div>";
    $i++;
};

Javascript:

$("#slide'.$i.'").click(function(){
    if ($("#slide'.$i.'").is(":hidden")) {
        $("#slide'.$i.'").show("slow");
    } else {
        $("#slide'.$i.'").slideUp();
    }
});

Conclusion:

I want to click a div (id=1 for example) and THAT div should open/close.

Upvotes: 0

Views: 97

Answers (2)

user3419778
user3419778

Reputation: 866

Use a class in your divs

$i = 0;
foreach($stock_history as $history){
    echo " 
    <div id='slide" . $i . "' class='slide-class'>
    <p>Date: <strong> " . $history->create_date . "</strong> </p> 
    <p>To: <strong> " . $history->toLocation->name . " </strong> </p> 
    <p>From: <strong> " . $history->fromLocation->name . " </strong> </p>
    <p>Moved by:  <strong> " .  $history->user->username . " </strong> </p>
    <hr />
    </div>";
    $i++;
}

And JS

$(".slide-class").click(function(){
    var current_id = this.id
    if ($("#"+current_id).is(":hidden")) {
        $("#"+current_id).show("slow");
    } else {
    $("#"+current_id).slideUp();
    }
  });

Upvotes: 2

SidOfc
SidOfc

Reputation: 4584

What I would suggest is that you give every slide a generalized classname for the effect and use that as a trigger to toggleClass() additional classes that will handle the actual state of the element.

if every element has a default class of .product-slide, you would use jQuery to toggle an additional class:

$('.product-slide').off('click.prod-slide').on('click.prod-slide', function() {
    $(this).toggleClass('specified-class');
});

Then in your CSS you could have .specified-class manipulate all the children inside with CSS.

This gives you the freedom to use CSS transitions instead of the much slower non hardware accelerated JS ones ;) (in case of 3d transitions - which you can force anyways)

On the click handler you can see my event is split by a .. This is just event namespacing. Avoiding conflicts with multiple handlers bound to the same element ;)

Hoping this helps you. Good luck!

Upvotes: 1

Related Questions