TheRev
TheRev

Reputation: 134

Trigger an anchor, open a modal and go to the anchor inside the modal

I'm trying to make a strange thing. I'll explain the general situation, then go with the step-by-step procedure that i want to do. I have a list of items inside an <ul>. When i press an element, a modal has to open. Inside this modal there are the same elements of the <ul> but explained in details. When the modal opens i want that the element that i have clicked inside the <ul> will be at the top of the modal body. Basically an anchor. Now the step-by-step

List of items (<li><a href="#some_element"></a></li>) I click an item(Click me!) The modal opens, showing the anchor

start_modal_body

<div id="some_element"></div>
<div id="not_this"></div>
<div id="not_this"></div>
<div id="not_this"></div>

end_modal_body

Any ideas?

Edit:

The modal and the rest of the code are in two separate files

Edit 2:

Since i'm using knockout, i can't use jquery to tell the modal to redirect me, this is why i was trying to use an anchor

Upvotes: 0

Views: 3364

Answers (1)

Carol Skelly
Carol Skelly

Reputation: 362380

Here's a CSS-only answer that might work if you're ok with re-ordering the positions of the anchor sections inside the modal, instead of scrolling to the top.

Wrap the modal buttons on another element an use that element to open the modal. Then the href inside the link will work to target the appropriate anchor...

<span data-target="#myModal" data-toggle="modal"><a href="#a" role="button" class="btn btn-primary">A</a></span>
<span data-target="#myModal" data-toggle="modal"><a href="#b" role="button" class="btn btn-primary">B</a></span>
<span data-target="#myModal" data-toggle="modal"><a href="#c" role="button" class="btn btn-primary">C</a></span>

<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            </div>
            <div class="modal-body d-flex flex-column">
                <div id="a">
                    ..
                </div>
                <div id="b">
                    ..
                </div>
                <div id="c">
                    ..
                </div>
            </div>
        </div>
    </div>
</div>

And use flexbox order to move the targeted section to the top of the modal...

.modal-body > div:target {
    order:0;
}

.modal-body > div:not(:target) {
    order:1;
}

Demo: https://www.codeply.com/go/HraCKrWHII

Upvotes: 1

Related Questions